0

如何使用我的显示成员是数组的值且值成员是数组键的数组填充 C# 中的组合框?

string[] RelayTypeArray = new string[4]; 
RelayTypeArray[0] = null; 
RelayTypeArray[1] = "Boiler"; 
RelayTypeArray[2] = "Valve"; 
RelayTypeArray[3] = "Pump"; 
cmb_RelayType.DataSource = RelayTypeArray; 
cmb_RelayType.DisplayMember = RelayTypeArray; 
cmb_RelayType.ValueMember = ?????
4

3 回答 3

5

只需按原样使用您的数组...

string[] RelayTypeArray = new string[4]; 
RelayTypeArray[0] = null; 
RelayTypeArray[1] = "Boiler"; 
RelayTypeArray[2] = "Valve"; 
RelayTypeArray[3] = "Pump"; 
cmb_RelayType.DataSource = RelayTypeArray; 

如果你想要文字:cmb_RelayType.SelectedValue

如果你想要索引:cmb_RelayType.SelectedIndex

于 2012-10-10T15:49:58.187 回答
0

如果你只是把 astring[]因为DataSource你不必定义 aDataMember或 a ValueMember。你可以简单地得到myComboBox.SelectedValueand myComboBox.SelectedIndex

DataMember-Property 仅描述要在您设置为的类型的 ComboBox 中显示的属性DataSource

例如,您设置了一个列表

class Test
{
    public string Name { get; set; }
    public int Id { get; set; }
}

作为DataSource并希望该框显示Name您必须设置的属性

myComboBox.DataMember = "Name";

ValueMember是 GUI 的“不可见”属性,您可以在其中存储值以供以后使用,例如:

myComboBox.ValueMember = "Id"

因此,如果有人通过显示选择一项,Name您可以Id从.ValueComboBoxItem

于 2012-10-10T15:44:08.860 回答
0

使用一个类并绑定它的集合:

class RelayType
{
    private int m_Index;
    private string m_Value;

    public RelayType(int index, string value)
    {
        m_Index = index;
        m_Value = value;
    }

    public int Index
    {
        get { return m_Index; }
    }

    public string Value
    {
        get { return m_Value; }
    }
}

var relayTypeCol = new List<RelayType>(); 
relayTypeCol.Add(new RelayType(0, ""));
relayTypeCol.Add(new RelayType(1, "Boiler"));
relayTypeCol.Add(new RelayType(2, "Valve"));
relayTypeCol.Add(new RelayType(3, "Pump"));

cmb_RelayType.DataSource = relayTypeCol; 
cmb_RelayType.DisplayMember = "Value"; 
cmb_RelayType.ValueMember = "Index";
于 2012-10-10T15:44:16.283 回答