Get the current index of a ComboBox?

后端 未结 3 408
心在旅途
心在旅途 2021-01-06 08:36

Say I had a ComboBox with these values:

Black
Red
Blue

And I have Red currently selected. If the user then hits backspace and

相关标签:
3条回答
  • 2021-01-06 08:42

    There is no inbuilt function to get the index for given value but you can find the index through this function.

    Usage:

    int cmbindex  = CmbIdxFindByValue("YourValue", cmbYourComboBox);
    

    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;
        }
    
    0 讨论(0)
  • 2021-01-06 09:01

    The way you are doing is fine. You have to keep the selected index in memory because it returns -1 as the SelectedIndex when the text is deleted. You could take the index in this way too.

    private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        currentMyComboBoxIndex = myComboBox.SelectedIndex;
    }
    
    0 讨论(0)
  • 2021-01-06 09:03

    You can use the following code to get the selected item of the combo box as an object:

    ComboBox comboBox = new ComboBox();
    // Initialize combo box
    comboBox.Items.Add("Black");
    comboBox.Items.Add("Red");
    comboBox.Items.Add("Blue");
    // Get selected one
    string current = (string)comboBox.SelectedItem;
    

    Also, the selected item can be easily removed by using one of the following lines of code:

    // By item
    comboBox.Items.Remove(comboBox.SelectedItem);
    // By Index
    comboBox.Items.RemoveAt(comboBox.SelectedIndex);
    
    0 讨论(0)
提交回复
热议问题