在foreach循环中创建控件?

时间:2010-12-30 14:27:14

标签: c# winforms

字符串数组包含一些文件位置。

我正在使用foreach循环,其中每个循环我想创建一个新的单选按钮控件。 没有foreach代码执行,但在循环中只有一个控件正在添加。

有人可以告诉我为什么吗?以及我如何执行此操作。

代码:

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);
    }
}

4 个答案:

答案 0 :(得分:2)

您将高度设置为100,但仅将位置增加30。

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

您可以将高度降低到30以下:

rbList.Height = 30; //or smaller

将“i”增加到100以上:

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

答案 1 :(得分:0)

添加

rbList.AutoSize = true;

并确保您的groupBox1足够大,以显示所有单选按钮。

答案 2 :(得分:0)

一点点变化:

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

groupBox1.Controls.Add(rbList);

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

这项工作没有对齐,对齐是你的。

答案 3 :(得分:0)

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