Premise:- We have a list of key value pairs.
The Item count of this list will vary.
We have a form with a bunch of default buttons on it. (Edit - Built earlier in the designer, not at runtime.)
The buttons are named "button1, button2, ..."
We have more buttons than items in the list.
At runtime we want to transfer information from the list elements to the buttons and hide the unused buttons.
My question is how to address those buttons from withing a loop?
Using a for loop in VBA I could say this:-
Me.Controls("TB_Item" & Format(i, "00")).Visible = False
In C# I have this minimal example as a starting point (The form has 10 buttons):-
public UF_ButtonLoop()
{
InitializeComponent();
List<KeyValuePair<string, string>> MyItems = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Apple", "Green Fruit"),
new KeyValuePair<string, string>("Orange", "Orange Fruit"),
new KeyValuePair<string, string>("Sprout", "Spawn of the Devil"),
new KeyValuePair<string, string>("Hershey Bar", "A bit like chocolate"),
new KeyValuePair<string, string>("Beefburger", "Man Food")
};
//Loop through the 10 buttons
for (int i = 1; i < 11; i++)
{
if (i <= MyItems.Count )
{
//Transfer Data from list to button
//Pseudo code
Control("Button" + i).Text = (MyItems.ElementAt(i).Key);
Control("Button" + i).Tag = (MyItems.ElementAt(i).Value);
}
else
{
//Hide the button as we've reached the end of the list so have no use for it.
//Pseudo code
Control("button" + 1).Hide();
}
// Note, VBA methos is:-
// Me.Controls("TB_Item" & Format(i, "00")).Visible = False
}
}
Control("Button" + i) is not correct syntax.
Can I do this in C#, if so how?
If not what is the correct way?
Also I'm new here so if I'm asking things in the wrong way please don't be shy in telling me so!
Many thanks, Owen S.
DataGridViewwith one column of type DataGridViewButtonColumn. DataGridView provide possibility to create buttons from the list with dynamic amount of items in it.this.Controls.OfType<Button>(). Unless you have placed them into a sub container.