Otiel
Otiel

Reputation: 18743

Retrieve comboBox displayed values

I am trying to retrieve the displayed values of all items present in a comboBox.

First case: if the comboBox has been filled using a DataSource:

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

...I use 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 has been filled with the comboBox.Items.Add("blah blah"), I use the same code, except I have to look in the first dimension of the 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 be able to retrieve all values without knowing the scheme used to fill the comboBox. Thus, I don't know if I have to use ItemArray[0] or ItemArray[1]. Is it possible? How could I do that?

Upvotes: 4

Views: 10481

Answers (3)

Jayanta Dey
Jayanta Dey

Reputation: 307

You can try something like this:

        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();
            }
        }

Upvotes: 4

Mamta D
Mamta D

Reputation: 6460

The Combobox would be populated with the DataSource property in the first case. Therefore its DataSource won't be null. In the second case, it would be null. So you could do an if-else with (comboBox1.DataSource==null) and then accordingly use ItemArray[0] or ItemArray[1].

Upvotes: 2

Grant Winney
Grant Winney

Reputation: 66499

Leito, you could check to see if the DataSource is a DataTable or not to determine which action to take.

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

Upvotes: 1

Related Questions