Search code examples
c#winformscombobox

C# Get SelectedIndex in ComboBox by name


I have to process some controls by their names

this.Controls.Find(String.Format("lbl{0}", index),
            true)[0].Text = data[i].ToString();

but when I tryed to get a Combobox by name it can't show the SelectedIndex property

this.Controls.Find(String.Format("cmbDat{0}", index), true)[0].

Who i can do?


Solution

  • You need to cast it to a ComboBox, because Find() returns a Control, which does not contain the SelectedIndex property.

    Try this instead:

    ComboBox theComboBox = this.Controls.Find(String.Format("cmbDat{0}", index), true) as ComboBox;
    
    // Verify the combo box was found before trying to use it
    if(theComboBox != null)
    {
        // Do whatever you want with the combo box here
        theComboBox.SelectedIndex = ???
        theComboBox.Text = ???
    }