您的位置:首页 > 其它

关于如何编辑绑定后的TextBox来完成对数据源的更新

2007-06-30 00:11 330 查看
问题:
窗口中控件绑定到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();
}
}
以下是可以成功更新数据库的一组代码:




全局变量#region 全局变量


SqlConnection conn=new SqlConnection();


SqlCommand com=new SqlCommand();


SqlDataAdapter da=null;


DataSet ds=new DataSet();


#endregion


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"];


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐