动态添加按钮

时间:2012-02-02 18:10:18

标签: c# forms

我正在创建一个表单,并在加载时从我的资源文件夹中获取所有图像,并为每个文件创建一个新按钮,将按钮背景图像设置为该图像并将该按钮添加到表单,但它只显示1个按钮,资源文件夹中有36个文件。

我的代码如下:

ResourceSet resourceSet = Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
    object resource = entry.Value;
    Button b = new Button();
    b.BackgroundImage = (Image)resource;
    b.BackgroundImageLayout = ImageLayout.Stretch;
    b.Height = 64;
    b.Width = 64;
    this.Controls.Add(b);
}

请协助我做错了什么。

1 个答案:

答案 0 :(得分:5)

我的猜测是代码确实添加了所有按钮,但它们都是彼此重叠的。每个按钮都有LeftTop的默认值,每个按钮的默认值都相同。由于按钮都具有相同的尺寸,因此只有顶部按钮可见。

通过为每个按钮设置LeftTop属性来解决问题。显然,每个不同的按钮需要具有LeftTop的不同值。


要回答您在评论中提出的问题,您可以按以下方式使用代码:

const int buttonSize = 64;
int left = 0;
int top = 0;
foreach (DictionaryEntry entry in resourceSet)
{
    object resource = entry.Value;
    Button b = new Button();
    b.BackgroundImage = (Image)resource;
    b.BackgroundImageLayout = ImageLayout.Stretch;
    b.Bounds = Rectangle(left, top, buttonSize, buttonSize);
    this.Controls.Add(b);

    // prepare for next iteration
    left += buttonSize;
    if (left+buttonSize>this.ClientSize.Width)
    {
        left = 0;
        top += 64;
    }
}
相关问题