MojtabaSh
MojtabaSh

Reputation: 637

How can find a combobox from string?

as I know combobox isn't member of System.Windows.Forms.Control class

I used this code for find control

Control ctrFindControl = this.Controls.Find("FindSomething", false)[0];

but how can find a combobox from string?

for (int i = 0; i <= cmbAccount1.Items.Count; i++)
{
   string txtCategory = "cmbCategory" + i;

   Control cmbBoxCategory;
   cmbBoxCategory = this.Controls.Find(txtCategory , false)[0];

   cmbBoxAccount.Items.Add("a");
   cmbBoxAccount.Items.Add("b");
   cmbBoxAccount.Items.Add("c");
   cmbBoxAccount.SelectedIndex = 0;
}

Upvotes: 0

Views: 51

Answers (1)

Grant Winney
Grant Winney

Reputation: 66469

You're almost there. Just cast the control you found to a ComboBox:

ComboBox cmbBoxCategory = (ComboBox)this.Controls.Find(txtCategory, false)[0];

cmbBoxCategory.Items.Add("a");
cmbBoxCategory.Items.Add("b");
cmbBoxCategory.Items.Add("c");
cmbBoxCategory.SelectedIndex = 0;

The ComboBox isn't a member of the Control class, but it is derived from it, which is why your current code compiles. You have to cast it to the more derived type, in this case a ComboBox, before you can access those members and properties that belong to a ComboBox.

Upvotes: 2

Related Questions