Sign in to follow this  
stake

[.net] Array of Widgets

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this