How to loop windows, increasing the number of objects

I have some web browsers on my C # application, I have 10. webBrowser0, webBrowser1, webBrowser2 etc.

In any case, I run a loop to count every screen, to place a web browser on every screen that I have, all this is done easily, but in my loop, if there is 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 can see, I am increasing the code quite a lot, so if I could link to webBrowser {index}, that would be fine, but that of course does not work.

+3
source share
4 answers

You can define an array

WebBrowser[] browsers = new WebBrowser[] { webBrowser0, webBrowser1, ... };

and use browsers[index]in your loop.

+4
source

Create a collection of your web browsers.

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;
    }
}
+5
source

,

var myBrowsers = new List<WebBrowser>().  

WebBrowsers

myBrowsers.Add(new WebBrowser());  // Do this 10 times for 10 browsers.

myBrowser[index]

foreach (var aBrowser in myBrowsers)
{
   aBrowser...
}

for (var i = 0; i < myBrowsers.Count; i++)
{
  myBrowser[i]...
}
+4

I recently worked with the same problem as many controls, and to find them all, I decided to use a list of controls (or just use Property controls on the form if you have ordered controls correctly), and then I looped on it, setting their location, calculating each position every time.

See you later.

0
source

All Articles