c#中的数据绑定-组合框的选定值到类的对象属性

本文关键字:对象 属性 数据绑定 组合 | 更新日期: 2023-09-27 18:09:39

我在c# windows Form项目中面临一些数据绑定问题。我使用。net Framework 4客户端配置文件。IDE是c#的visual studio 2010 express edition。我有一个类如下。

public myClass()
    {
        name = string.Empty;
        dataType = DataTypes.Bool;  //property with enum created by me
        isList = false;
        filterValue = new object();
    }

那么我有一个profile.csv文件。在我的一个表单中,我有一个组合框,它的数据源是datatable,其中包括来自csv文件的数据。

private void form_load()
{
 ComboBox comboBox = new ComboBox();
 this.Controls.Add(comboBox);
 comboBox.Name = attribute.Name.Replace(" ", string.Empty);
 comboBox.DisplayMember = attribute.Name;
 comboBox.DataSource = attributeValueDataSource.Tables[tableName].DefaultView;
 comboBox.SelectedIndex = 0;
}

然后我将这个组合框绑定到我的类。由于我的数据绑定在另一个不同于上面的方法中,并且组合框是动态创建的,所以我在下面的方法中找到了我的组合框的名称。

private void Method_1
{
control = this.Controls.Find(attrName, true); 
ComboBox specificControl = (ComboBox)control[0]; Binding attributeBinding = 
new Binding(SelectedValue, attributeSelectionController.FilterAttributeModels[attributeCount] , FilterValue, true, DataSourceUpdateMode.OnPropertyChanged, string.Empty, F); 
attributeBinding.ControlUpdateMode =   ControlUpdateMode.OnPropertyChanged;   specificControl.DataBindings.Add(attributeBinding);
 }

在那个状态之前看起来很好。但是当绑定事件调用和程序流转到set属性方法时,value.GetType()返回system.data.datarowview作为组合框项的selectedValue类型,而不是字符串或整数或任何其他数据类型。当我将数据源设置为其时,我已尝试为组合框设置值成员。但是没有帮助。有人能帮忙吗?我需要紧急解决办法。

c#中的数据绑定-组合框的选定值到类的对象属性

终于可以算出问题了。在form load方法中,我改变了下面行的顺序。

comboBox.DisplayMember = attribute.Name; 
comboBox.DataSource = attributeValueDataSource.Tables[tableName].DefaultView;

comboBox.DataSource = attributeValueDataSource.Tables[tableName].DefaultView;
comboBox.DisplayMember = attribute.Name;
combox.ValueMember = attribute.Name;

那就行了。:)

我要感谢帮助我的朋友。