将对象设置为新实例时单向绑定不起作用

时间:2013-10-29 15:19:42

标签: c# winforms data-binding

我有一个名为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 为空。

注意:我注意到,一旦btnNext_Click方法代码块结束(在dubuggin上),它就会遍历数据库中的所有实体(我看到它,在调试时,它会通过所有在EDMX设计师,我可以看到它获取表中可用的所有值。

1 个答案:

答案 0 :(得分:1)

当然这样做。当您更改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);
相关问题