【问题标题】:Detecting invalid data in the data binding source检测数据绑定源中的无效数据
【发布时间】:2011-05-06 17:40:51
【问题描述】:

我有一个带有基于对象数组的 DataSource 的组合框,Value 属性绑定到模型存储库上的属性:

DataSource = someArray;
ValueMember = "ArrayValue";
DisplayMember = "Name";
DataBindings.Add("Value", repository, "RepositoryValue");
DataBindings["Value"].DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged;

在某些情况下,用户更改组合框中的选定项并反映在repository.RepositoryValue中,有时我们从文件或数据库中提取数据并直接填充repository.RepositoryValue,然后自动反映在组合框中.有时文件或数据库可能包含无效值(someArray 中未包含的值),我们希望检测这种情况并强制组合框选择列表中的第一项或完全拒绝更改.这可能吗?我们应该如何去做?

【问题讨论】:

    标签: c# winforms data-binding


    【解决方案1】:

    可以使用Binding的Format事件来处理。

    Binding SelectedValueBinding = new Binding("SelectedValue", repository, "RepositoryValue", true, DataSourceUpdateMode.OnPropertyChanged);
    SelectedValueBinding.Format += new ConvertEventHandler(SelectedValueBinding_Format);
    myComboBox.DataBindings.Add(SelectedValueBinding);
    
    void SelectedValueBinding_Format(object sender, ConvertEventArgs e)
    {
            // if e.Value is Invalid
            // myComboBox.SelectedValue = "Default Value";
    }
    

    查看更多:

    How does one databind a custom type to TextBox.Text?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多