问题:
窗口中控件绑定到dataSet1上,但调用this.BindingContext[this.dataSet1].EndCurrentEdit();
程序并没有将当前的最新编辑存入dataSet1,
解决方法:
MSDN中说明了BindingContext的索引访问总是会返回一个BindingManagerBase,所以
即使你传入了一个错误的参数,例如
this.DataSet1也会有返回值,所以造成错误的认为调用是正确的。
DataSet的绑定实际上内部是使用DataView实现的,所以有俩种解决方法:
1、将控件绑定到DataView,而DataView关联DataSet,结束编辑时调用:
BindingContext[this.dataview1].EndCurrentEdit();
但这种方法如果有俩个表或更多调用就麻烦一些。
2、直接寻找所有的绑定环境,并结束编辑。
BindingManagerBase bm;
foreach (System.Collections.DictionaryEntry item in
this.BindingContext) {
bm = (item.Value as System.WeakReference).Target as
BindingManagerBase;
if (bm != null) {
bm.EndCurrentEdit();
}
}
以下是可以成功更新数据库的一组代码:
全局变量
private void Form1_Load( object sender, System.EventArgs e)
{
conn.ConnectionString="Server=.;Trusted_connection=true;DataBase=Northwind";
com=conn.CreateCommand();
com.CommandText="select * from Region";
da=new SqlDataAdapter(com);
SqlCommandBuilder comb=new SqlCommandBuilder(da);
da.Fill(ds,"region");
this.DBind();
this.textBox1.DataBindings.Add("Text",ds.Tables["region"],"RegionID");
this.textBox2.DataBindings.Add("Text",ds.Tables["region"],"RegionDescription");
}
private void button1_Click( object sender, System.EventArgs e)
{
//这一句是为了结束所有被绑定的控件结束编辑状态,可以写如下的
//第1种:
BindingManagerBase myBind=this.BindingContext[this.ds.Tables["region"]];
myBind.EndCurrentEdit();
//第2种:
//this.BindingContext[this.ds.Tables["region"]];
//以上两种编辑方法都可以结束控件
da.Update(ds,"region");
this.DBind();
}
private void DBind()
{
this.dataGrid1.DataSource=ds.Tables["region"];
}