我有一个名为 Tel 的对象,它绑定到三个控件,如下所示。
this.txtTelName.DataBindings.Add("Text", tel, "T_Name", false, DataSourceUpdateMode.OnPropertyChanged);
this.chkActive.DataBindings.Add("Checked", tel, "T_Active", true, DataSourceUpdateMode.OnPropertyChanged);
this.txtNotes.DataBindings.Add("Text", tel, "T_Notes", true, DataSourceUpdateMode.OnPropertyChanged);
这将成功提示对象在控件中的所有值。
我需要实现一个 Next 按钮,它允许用户通过保存 tel 对象来保存控件上的值,然后使用新实例创建 tel 对象并清理所有控件。因此,用户可以添加新记录。
这是下一个按钮代码:
private void btnNext_Click(object sender, EventArgs e)
{
BllTel.Save(tel); //Saves the Tel entity
this.tel = new Model.DatabaseModels.Tel();
tel.T_Active = BusinessLogic.Enums.StatusCodes.Active;
txtTelName.Text = "";
txtNotes.Text = "";
}
直到这里一切正常,但是在用户第二次添加后,tel 对象不会绑定他们在控件中写入的值,而是将T_Name和T_Notes为 null。
注意:我注意到一旦btnNext_Click方法代码块结束(在dubuggin上),它就会遍历数据库中的所有实体(我看到它,在调试时,它通过EDMX设计器中定义的所有属性,我可以看到它获取表中所有可用的值)。
它当然是这样工作的。当您更改 tel
的实例时,它不再绑定到您的其他控件。因此,您应该定义一些方法来绑定它们之间的数据并重新调用此方法:
public void BindData(object tel){
if(txtTelName.DataBindings["Text"] != null)
txtTelName.DataBindings.Remove(txtTelName.DataBindings["Text"]);
txtTelName.Add("Text", tel, "T_Name", false, DataSourceUpdateMode.OnPropertyChanged);
if(chkActive.DataBindings["Checked"] != null)
chkActive.DataBindings.Remove(chkActive.DataBindings["Checked"]);
chkActive.DataBindings.Add("Checked", tel, "T_Active", true, DataSourceUpdateMode.OnPropertyChanged);
if(txtNotes.DataBindings["Text"] != null)
txtNotes.DataBindings.Remove(txtNotes.DataBindings["Text"]);
txtNotes.DataBindings.Add("Text", tel, "T_Notes", true, DataSourceUpdateMode.OnPropertyChanged);
}
//then use it like this:
tel = new Model.DatabaseModels.Tel();
tel.T_Active = BusinessLogic.Enums.StatusCodes.Active;
BindData(tel);