【发布时间】:2011-01-25 23:14:49
【问题描述】:
我正在使用针对 SqlCe 数据库的 C#.Net 开发手持设备。我有一个带有多个面板的表单,每个面板都有自己的一组文本框控件。构建表单后,我将每个文本框控件自动绑定到我从数据库查询的表中匹配的列名。例如:txtFld1 = ResultTable.Fld1、txtFld2 = ResultTable.Fld2 等。所有这些都没有问题。如果我在表中查询给定的记录 ID,则表单刷新没有问题。如果我单击表单上的按钮并手动更改一个或多个字段的表中单行的值,则表单不会反映这些更改...例如:
DataRow oDR = MySQLResultTable.Rows[0];
oDR["Fld1"] = "Something";
oDR["Fld2"] = "else";
oDR["Fld3"] = "changed";
表单上的 3 个字段不反映这些更改的值。但是,如果我键入特定字段,则这些值将被推回 MySQLResultTable 的相应数据行,Row[0] 对象。
我错过了什么。
谢谢
在它的简化格式中,因为我确定了控件的名称并在表中找到了相应的列名,这就是我所拥有的
public void BindControlsToDataTable(Control Page, DataTable oTbl )
{
String cObjName;
foreach (Control oCtrl in Page.Controls)
{
// if this control has other controls, bind them too...
if (oCtrl.Controls.Count > 0)
BindControlsToDataTable(oCtrl, oTbl);
// Now, try to do dynamic binding. The controls are created
// based on a 3 char prefix such as "txt", "cbo", "chk", etc
// with the remainder as the object name they represent...
// ex: txtDescription, txtFirstName, txtLastName, chkIsOk, etc..
cObjName = oCtrl.Name.Substring(3);
if (oTbl.Columns[lcName] != null)
{
oCtrl.DataBindings.Clear();
// we are binding the "TEXT" property of the control
// to the column name in the table/row
oCtrl.DataBindings.Add("Text", oTbl, cObjName,true,
DataSourceUpdateMode.OnPropertyChanged);
}
}
}
同样,如果我的文本框字段是 txtMyFld1,并且表中对应的列名是 MyFld1,它们将自动配对。我在初始化表单并且准备/运行我的第一个查询以填充 DataTable 对象并绑定后调用它。
HTH
【问题讨论】:
-
能否在您的问题中添加数据绑定初始化代码?
标签: c# data-binding refresh