使用bindingsoure更新数据源没有语法错误 就是不显示
using System;using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.
namespace WindowsFormsApplication35
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.bindingSource1.DataSource = clsdb.Instance.getData();//指定数据源
this.btpre.Click += new EventHandler(btpre_Click);
this.btnext.Click += new EventHandler(btnext_Click);
this.btsave.Click += new EventHandler(btsave_Click);
this.txtname.DataBindings.Add("text", bindingSource1, "ProductName");//绑定控件
this.txtprice.DataBindings.Add("text", bindingSource1, "UnitPrice");
}
void btsave_Click(object sender, EventArgs e)
{
this.bindingSource1.EndEdit();//结束当前编辑
clsdb.Instance.Save(this.bindingSource1.DataSource as DataTable);
}
void btnext_Click(object sender, EventArgs e)
{
this.bindingSource1.MoveNext();//导航到下一记录
}
void btpre_Click(object sender, EventArgs e)
{
this.bindingSource1.MovePrevious();//导航到上一记录
}
class clsdb
{
private SqlDataAdapter adapter = null;
private static clsdb clsdbobject = null;//一个静态clsdb的对象
public static clsdb Instance
{//静态属性如果clsdbobject为空就构造一个实例
get
{
if(clsdbobject==null)
{
clsdbobject=new clsdb();
}
return clsdbobject;
}
}
private clsdb()
{
InitAdapter();
}//私有构造函数,在类外不能用new实例化
private void InitAdapter()
{//初始化dadpter的对象
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "Persist Security Info=False;Integrated Security=SSPI;Initial Catalog=Northwind;server=(local)";
adapter = new SqlDataAdapter("select ProductID,ProductName,UnitPrice from Products",connection);
adapter.FillLoadOption = LoadOption.OverwriteChanges;//修改
SqlCommand ud = new SqlCommand();
ud.Connection = cn;
= "update Products set ProductName=@ProductName,UnitPrice=@UnitPrice where ProductID=@ProductID";
ud.Parameters.Add("@ProductID", SqlDbType.Int, 4, "ProductID");
ud.Parameters.Add("@ProductName", SqlDbType.VarChar, 20, "ProductName");
ud.Parameters.Add("@UnitePrice", SqlDbType.Money, 10, "UnitPrice");
adapter.UpdateCommand = ud;
}
public int Save(DataTable dt)
{//保存数据,如果保存失败就返回-1
int ret = 0;
try
{
ret = adapter.Update(dt);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
ret = -1;
}
return ret;
}
public DataTable getData()
{//获取数据
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
return dt;
}
public SqlConnection connection { get; set; }
}
private void btsave_Click_1(object sender, EventArgs e)
{
}
}
}