C#中的DataBind - 一个类的ComboBox to Object属性的selectedvalue

时间:2013-04-18 04:13:08

标签: c# winforms data-binding combobox selectedvalue

我在C#windows Form项目中遇到了数据绑定的问题。我使用.Net Framework 4客户端配置文件。 IDE是针对C#的visual studio 2010 express版。我有一个课程如下。

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

然后我有一个profile.csv文件。在我的一个表单中,我有一个组合框,它的数据源是数据表,其中包含来自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作为combobox项的selectedValue的类型,而不是字符串或整数或任何其他数据类型。我设置数据源到它时,我试图为combox设置值成员。但没有帮助。任何人都可以帮忙吗?我需要紧急解决方案。

1 个答案:

答案 0 :(得分:1)

最后可以找出问题所在。在表单加载方法中,我改变了以下行的顺序。

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

as

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

然后它有效。 :)

**我的朋友帮助了我。