简体   繁体   中英

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

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

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

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 !!

OP: What I want is to get index from value. ie: 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;
}

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM