[.net] Array of Widgets

Started by
1 comment, last by dalep 17 years, 1 month ago
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?
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
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.

This topic is closed to new replies.

Advertisement