Retrieve comboBox values

I am trying to get the displayed values ​​of all the elements present in comboBox.

The first case : if the comboBox was filled with DataSource:

comboBox.DataSource = myDataSet.Tables[0];
comboBox.DisplayMember = "value";
comboBox.ValueMember = "id";

... I am using this code:

foreach (DataRowView rowView in comboBox.Items) {
    String value = rowView.Row.ItemArray[1].ToString();
    // 1 corresponds to the displayed members
    // Do something with value
}

Second case : if the comboBox was filled with comboBox.Items.Add("blah blah"), I use the same code, except that I need to look in the first dimension ItemArray:

foreach (DataRowView rowView in comboBox.Items) {
    String value = rowView.Row.ItemArray[0].ToString();
    // 0 corresponds to the displayed members
    // Do something with value
}

Now I would like to get all the values ​​without knowing the schemes used to populate the comboBox. So I do not know if I should use ItemArray[0]or ItemArray[1]. Is it possible? How can i do this?

+5
source share
3 answers

- :

        string displayedText;
        DataRowView drw = null;

        foreach (var item in comboBox1.Items)
        {
            drw = item as DataRowView;
            displayedText = null;

            if (drw != null)
            {
                displayedText = drw[comboBox1.DisplayMember].ToString();
            }
            else if (item is string)
            {
                displayedText = item.ToString();
            }
        }
+4

Combobox DataSource. DataSource . null. , if-else (comboBox1.DataSource==null), ItemArray[0] ItemArray[1].

+2

Leito, you can check if the DataSource is DataTable or not to determine what action to take.

if (comboBox.DataSource is DataTable)
{
    // do something with ItemArray[1]
}
else
{
    // do something with ItemArray[0]
}
+1
source

All Articles