数据绑定UI中的多个字段不更新

时间:2011-03-08 12:29:23

标签: winforms data-binding dataset

我有一个winform,其中包含一个绑定源,其数据源是一个类型化数据集。我已将设计器中的两个文本框绑定到同一列。当我更新任一文本框时,DatSet中的DataRow列已正确更新,但表单上的其他文本框值不会更新。

我错过了什么?如何获取数据绑定以更新第二个文本框?

注意:这是我需要执行此操作的简化示例,因为在实际应用程序中,因为一个控件可由用户编辑,另一个控件是用于计算的复合控件的输入。

// Taken from InitializeComponent()
this.productsBindingSource.DataMember = "Products";    
this.productsBindingSource.DataSource = this.dataSet1;
this.textBox1.DataBindings.Add(new Binding("Text", this.productsBindingSource, "UnitsInStock", true, DataSourceUpdateMode.OnPropertyChanged));
this.textBox2.DataBindings.Add(new Binding("Text", this.productsBindingSource, "UnitsInStock", true, DataSourceUpdateMode.OnPropertyChanged));

// Taken from Form Load Event          
DataSet1TableAdapters.ProductsTableAdapter adapter = new DataSet1TableAdapters.ProductsTableAdapter();
adapter.Fill(dataSet1.Products);

2 个答案:

答案 0 :(得分:1)

MSDN上有一篇文章可能有所帮助 - 请参阅How to: Ensure Multiple Controls Bound to the Same Data Source Remain Synchronized

基本上你需要为BindingSource的BindingComplete事件设置事件处理程序(正如你所做的那样,你需要将FormattingEnabled设置为True才能使其工作)

然后,在BindingComplete事件处理程序中,您有以下代码:

    private void productsBindingSource_BindingComplete(object sender, BindingCompleteEventArgs e)
        {
            // Check if the data source has been updated, 
            // and that no error has occured.
            if (e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate && e.Exception == null)
            {
                // End the current edit.
                e.Binding.BindingManagerBase.EndCurrentEdit();
            }
        }

答案 1 :(得分:0)

所以我的解决方案是在Typed Data Row类上实现INotifyPropertyChanged,因为它被设计者公开为部分类,这是相当直接的,然后将bindingsource的数据源设置为数据行本身。

public partial class MyDataRow : INotifyPropertyChanged
{
    public void AddEventHandler()
    {
        this.Table.ColumnChanged += new System.Data.DataColumnChangeEventHandler(Table_ColumnChanged);
    }

    void Table_ColumnChanged(object sender, System.Data.DataColumnChangeEventArgs e)
    {
        OnPropertyChanged(e.Column.ColumnName);
    }
    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion
}

数据绑定代码

MyDataRow row = <Get Current Row>;
row.AddEventHandler();
bindingSource1.DataSource = row;