开发者

Retrieve comboBox displayed values

开发者 https://www.devze.com 2023-04-08 05:31 出处:网络
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:

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 开发者_JS百科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?


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


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].


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]
}
0

精彩评论

暂无评论...
验证码 换一张
取 消