簡體   English   中英

如何從組合框 C# 中的選定值中獲取選定索引

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

是否有任何內置方法可以從 ComboBox 控件 C# 中的選定值中獲取選定索引。 如果沒有,我如何建立自己的

提前致謝

我認為您正在尋找 SelectedIndex 屬性。

int index = comboref.SelectedIndex

當您正在尋找特定值的索引而不是您可以執行的選定值時

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

它會告訴你哪個索引在組合框上有“字符串”

您可以使用combobox1.Items.IndexOf("string")它將返回指定項目集合內的索引

或者使用combobox1FindString("string")findExactString("string")這將返回指定項目的第一次出現。 您還可以為它提供與startIndex相對應的第二個參數,以從該索引開始搜索。

我希望我回答了你的問題!!

OP:我想要的是從值中獲取索引。 即:int seletedIndex = comboBox.getIndexFromKnownSelectedValue(value)

按值獲取項目並按獲取索引

您需要掃描項目並為每個項目獲取基於SelectedValue字段的值,然后獲取項目的索引。 為此,您可以使用此GetItemValue擴展方法並通過以下方式獲取項目和索引:

//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;
}

不,沒有任何內置方法可以從 ComboBox 控件 C# 中的選定值中獲取選定索引。 但是您可以創建自己的函數來實現相同的功能。

用法:

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

功能:

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;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM