How to get selected index from selected value in combo box C#

风流意气都作罢 提交于 2020-01-25 17:33:56

问题


Is there any built-in method for getting selected index from selected value in ComboBox control C#. If not, how can I built my own one

Thanks in advance


回答1:


I think you're looking for the SelectedIndex property.

int index = comboref.SelectedIndex

As you're looking for the index of a specific value not the selected one you can do

int index = comboref.Items.IndexOf("string");

and it will tell you which Index has "string" on the combobox




回答2:


You can use combobox1.Items.IndexOf("string") which will return the index within the collection of the specified item

Or use combobox1FindString("string") or findExactString("string") which will return the first occurence of the specified item. You can also give it a second parameter corresponding to the startIndex to start searching from that index.

I Hope I answered your question !!




回答3:


OP: What I want is to get index from value. i.e: int seletedIndex = comboBox.getIndexFromKnownSelectedValue(value)

Get Item by Value and Get Index by Value

You need to scan the items and for each item get the value based on the SelectedValue field and then get the index of item. To do so, you can use this GetItemValue extension method and get item and index this way:

//Load sample data
private void Form1_Load(object sender, EventArgs e)
{
    comboBox1.DataSource = Enumerable.Range(1, 5)
        .Select(x => new { Name = $"Product {x}", Id = x }).ToList();
    comboBox1.DisplayMember = "Name";
    comboBox1.ValueMember = "Id";
}

private void button1_Click(object sender, EventArgs e)
{
    //Knows value
    var value = 3;

    //Find item based on value
    var item = comboBox1.Items.Cast<Object>()
        .Where(x => comboBox1.GetItemValue(x).Equals(value))
        .FirstOrDefault();

    //Find index 
    var index = comboBox1.Items.IndexOf(item);

    //Set selected index
    comboBox1.SelectedIndex = index;
}



回答4:


No, there is no any built-in method for getting selected index from selected value in ComboBox control C#. But you can create your own function to get the same.

Usage:

int index = CmbIdxFindByValue("YourValue", YourComboBox);

Function:

private int CmbIdxFindByValue(string text, ComboBox cmbCd)
{
    int c = 0;
    DataTable dtx = (DataTable)cmbCd.DataSource;
    if (dtx != null)
    {
        foreach (DataRow dx in dtx.Rows)
        {
            if (dx[cmbCd.ValueMember.ToString()].ToString() == text)
                return c;
            c++;
        }
        return -1;
    } else
        return -1;

}


来源:https://stackoverflow.com/questions/27764755/how-to-get-selected-index-from-selected-value-in-combo-box-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!