How to loop windows forms objects incremently
I have s开发者_C百科ome webBrowsers on my C# application, infact I have 10. webBrowser0, webBrowser1, webBrowser2 and so on..
Anyways, I'm performing a loop to count each screen to place a webBrowser on each screen I have, all this is done easily, but in my loop, if have something like this.
for (index = 0; index <= totalScreens; index++)
{
if (index == 0)
{
webBrowser0.Width = x;
webBrowser0.Height = x;
}
if (index == 1)
{
webBrowser1.Width = x;
webBrowser1.Height = x;
}
}
As you cansee, I'm doubling up on code quite a lot, so if I could refer to webBrowser{index} that would be perfect but that of course isn't working.
Create collection of your WebBrowsers.
List<WebBrowser> browsers = new List<WebBrowser> {webBrowser0,webBrowser1};
for (index = 0; index <= totalScreens; index++)
{
if(index < browsers.Count)
{
browsers[index].Width = x;
browsers[index].Height = x;
}
}
You could define an array
WebBrowser[] browsers = new WebBrowser[] { webBrowser0, webBrowser1, ... };
and use browsers[index]
in your loop.
What you could do is use
var myBrowsers = new List<WebBrowser>().
Then you add your WebBrowsers with
myBrowsers.Add(new WebBrowser()); // Do this 10 times for 10 browsers.
In that way you can use
myBrowser[index]
or to access each one in a loop
foreach (var aBrowser in myBrowsers)
{
aBrowser...
}
or
for (var i = 0; i < myBrowsers.Count; i++)
{
myBrowser[i]...
}
I was working recently with the same problem as you lots of controls and a for to locate them all, I've chosen to use a List of controls (or simply use the Property Controls in the form if you have the controls ordered correctly) and then I looped over it setting their location calculating each position each time.
See you.
精彩评论