DataGridView与TextBox的绑定
本文讲述DataGridView中的当前行数据怎样自动绑定到TextBox等其他编辑控件。
在进行WinForm编程时,编辑通常通过两种方式进行,一是网格操作,即数据的新增、维护、删除等操作均在网格中进行,一是通过文本框、下了列表、日期等控件逐条编辑。后者往往和网格相关联,即单击网格中某一行时,希望该行数据显示到相对应的文本框等控件中,在这些控件编辑后,数据的改动又同时反应到网格中。
我们本文只讨论第二种方式的操作。中规中矩的方式是,在DataGridView控件的Click事件中编写若干代码,将DataGridView的当前行中的数据逐个写到相对应的文本框等控件中。
有没有其他更好的写法了呢? 将文本框的所有属性都看了一遍,与数据绑定有关的属性好像就只有DataBindings了,日期控件、下拉框控件等都有此属性,如下代码就是使用该属性进行数据绑定的例子,例子中网格控件(dgAccount)和其他编辑使用同一个数据源(accounts),当点击网格中某一行数据时,该行数据就自动更新到编辑控件了。
private void Query()
{
//dgInOut为DataGridView控件
IList<AccountInfo> accounts = accountBLL.GetList();
this.dgAccount.DataSource = accounts;
{
//dgInOut为DataGridView控件
IList<AccountInfo> accounts = accountBLL.GetList();
this.dgAccount.DataSource = accounts;
//如下代码实现,单击网格时,自动将网格中当前行的相应列赋值给日期、文本等控件的相应属性中。
this.txtCode.DataBindings.Clear();
this.txtCode.DataBindings.Add("Text", accounts, "Code");
this.rbIn.DataBindings.Clear();
this.rbIn.DataBindings.Add("Tag", accounts, "Direction");
this.rbIn.DataBindings.Add("Tag", accounts, "Direction");
this.txtID.DataBindings.Clear();
this.txtID.DataBindings.Add("Text", accounts, "ID");
//可添加绑定数据变化时的触发处理
this.txtName.DataBindings.Clear();
this.txtName.DataBindings.Add("Text", accounts, "Name").Format += new ConvertEventHandler(Account_Format);
}
this.txtName.DataBindings.Clear();
this.txtName.DataBindings.Add("Text", accounts, "Name").Format += new ConvertEventHandler(Account_Format);
}
void Account_Format(object sender, ConvertEventArgs e)
{
if (rbIn.Tag.ToString() == "收")
this.rbIn.Checked = true;
else
this.rbOut.Checked = true;
}
以上数据集合使用DataTable也可达到同样的要过。