• Advertisement
Sign in to follow this  

[.net] Array of Widgets

This topic is 3995 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I was wondering if there was a way to create an array of widgets in the GUI designer of Visual Studio 2005. For example I would like to have 10 labels and have the ability to iterate over the labels with something like a for loop. What would be the best method for doing this? Is this possible with the GUI designer or would I have to code the widgets by hand? Has anyone done this?

Share this post


Link to post
Share on other sites
Advertisement
Code it by hand. Pretty easy to do.


private void Form1_Load(object sender, EventArgs e)
{

for (int count = 0; count < 10; count++)
{
string temp_Name = "Label" + count.ToString();
Point loc = new Point(20, count * 20);
CreateLabel(temp_Name, loc);
}

}

private void CreateLabel(string name, Point location)
{
Label temp_Label = new Label();
temp_Label.Text = name;
temp_Label.Location = location;
temp_Label.AutoSize = true;
this.Controls.Add(temp_Label);

}



That should do it for ya.
theTroll

Share this post


Link to post
Share on other sites
If they are the only labels on the form, you can iterate over the controls collection like this:


foreach(Control c in Controls)
{
Label label = c as Label;
if(label != null)
{
// Do something to the label
}
}


The "as" operator there both filters out non-label controls and typecasts for you.

If there are other labels on the form that you don't want to include in the iteration or something else making things more complicated (like the labels don't all have the same parent control) then the best thing to do is create a List and stick the labels you're interested into that during initialization.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement