johnnie
johnnie

Reputation: 2057

adding buttons dynamically

I am creating a form, and on load it gets all images from my resources folder and for each file creates a new button, sets the buttons background image to that image and adds that button to the form, but it is only displaying 1 button and there are 36 files in the resources folder.

My code is as follows:

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

Please assist on what I am doing wrong.

Upvotes: 0

Views: 89

Answers (1)

David Heffernan
David Heffernan

Reputation: 613562

My guess is that the code is indeed adding all the buttons but that they are all on top of each other. Each button will have a default value for Left and Top and those default values will be the same for each button. Since the buttons all have the same size, only the top button is visible.

Solve the problem by setting the Left and Top properties for each button. Obviously each different button needs to have a different value for Left and Top.


To answer the question you ask in a comment, you could use code along these lines:

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

Upvotes: 5

Related Questions