So I have an array that has the first portion of comboboxes on an order form. the comboboxes hold data (x1, x2, x3, x4), and are named ketchupCount, mustardCount, etc...
What I am trying to do is use the array normalCondoments array + Count to generate the correct combobox name to set the SelectedIndex value to -1 which is unselected. Eventually It will get the value, not set it, and print it to a string...
The expected code should read ketchupCount.SelectedIndex
string[] normalCondoments = { "ketchup", "mustard", "mayo", "ga",
"lettuce", "tomato", "pickles", "onion" };
foreach (var nCondoment in normalCondoments)
{
string str = nCondoment + "Count";
MessageBox.Show("letter:" + nCondoment);
str.SelectedIndex = -1;
}
The error I am getting is:
"String does not contain a selected definition for 'SelectedIndex' and no accessable extension for 'SelectedIndex' accepting a first argument of type 'string' ncould be found."
VS doesnt give a fix for this, I have looked and looked, but havent found something similar to this error. Thanks in advance
You can get a reference of a Control using the Container.Controls[] collection.
This collection can be indexed by a Int32
value or a String
, representing a Control's name.
In your case, if the ComboBoxes are all direct children of the Form, your code could be:
string[] normalCondoments = { "ketchup", "mustard", "mayo", "ga",
"lettuce", "tomato", "pickles", "onion" };
foreach (var nCondoment in normalCondoments) {
(this.Controls[$"{nCondoment}Count"] as ComboBox).SelectedIndex = -1;
}
Otherwise, replace this
with the actual container.
If instead these controls are children of different containers, you need to find them.
In this case, use the Controls collection's Find() method, specifying to searchAllChildren
:
foreach (var nCondoment in normalCondoments) {
var cbo = (this.Controls.Find($"{nCondoment}Count", true).FirstOrDefault() as ComboBox);
if (cbo != null) cbo.SelectedIndex = -1;
}