Reputation: 119
How can I populate a combo box in C# with an array that my display member is the value of array and the value member is the array key?
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 = ?????
Upvotes: 0
Views: 6550
Reputation: 3297
If you just put a string[]
as DataSource
you don't have to define a DataMember
or a ValueMember
.
You can simply get the myComboBox.SelectedValue
and myComboBox.SelectedIndex
.
The DataMember
-Property just describes a property to display in the ComboBox of the type you set as DataSource
.
For example you set a List of
class Test
{
public string Name { get; set; }
public int Id { get; set; }
}
as DataSource
and want the box to display the Name
property you have to set
myComboBox.DataMember = "Name";
The ValueMember
is an "invisible" property for the GUI where you can store values for later use, for example:
myComboBox.ValueMember = "Id"
So if someone chooses one item by its displayed Name
you can get the Id
from the Value
(don't know the propper name by heart) property of the ComboBoxItem
.
Upvotes: 0
Reputation: 22001
just use your array as it is...
string[] RelayTypeArray = new string[4];
RelayTypeArray[0] = null;
RelayTypeArray[1] = "Boiler";
RelayTypeArray[2] = "Valve";
RelayTypeArray[3] = "Pump";
cmb_RelayType.DataSource = RelayTypeArray;
if you want the text: cmb_RelayType.SelectedValue
if you want the index: cmb_RelayType.SelectedIndex
Upvotes: 5
Reputation: 2709
Use a class and bind it's collection:
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";
Upvotes: 0