开发者

Create Control in foreach loop?

There is string a开发者_开发问答rray contains some file location.

I am using a foreach loop, in which each loop i want to create a new radio button control. without foreach code performs, but in loop only one control is adding.

Can anybody tell me why? and how I perform this.

Code:

string[] location =
{
    @"C:\Program Files\Skype\Phone\Skype.exe",
    @"C:\Program Files\iTunes\iTunes.exe",
    @"C:\Program Files\Internet Explorer\iexplore.exe"
};

int i = 10;
foreach (string path in location)
{
    if (File.Exists(path))
    {
        RadioButton rbList = new RadioButton();
        rbList.AutoSize = false;
        Icon icn;
        icn = Icon.ExtractAssociatedIcon(path);
        rbList.Image = icn.ToBitmap();
        rbList.Height = 100;
        rbList.Width = 50;
        i = i + 30;
        rbList.Location = new Point(100, i);

        groupBox1.Controls.Add(rbList);
    }
}


You set the height to 100 but increase the position by 30 only.

rbList.Height = 100; 
...
i = i + 30;
rbList.Location = new Point(100, i);

You can decrease the height below 30:

rbList.Height = 30; //or smaller

or

increase the "i" more than 100:

i = i + 100; //or more than 100
rbList.Location = new Point(100, i);


Add

rbList.AutoSize = true;

And be sure your groupBox1 is large enough to display all your radio buttons.


Little bit of changes:

i = i + 100;
rbList.Location = new Point(100, i);

groupBox1.Controls.Add(rbList);

int space = 10;
groupBox1.Height += rbList.Height + space;

This work without alignment, alignment is yours.


int i = 10;
var radios = new[] { "", "", "" }
    .Where(path => File.Exists(path))
    .Select(path => new RadioButton
        {
            AutoSize = false,
            Image = Icon.ExtractAssociatedIcon(path).ToBitmap(),
            Height = 100,
            Width = 50,
            Location = new Point(100, (i = i + 30))
        })
     .ToArray();

groupBox1.Controls.AddRange(radios);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜