0

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.

1 Answer 1

5

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;
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I just set the top and left properties for the button, the button is indeed moving but still displaying the one button.
Did you set the Left and Top values to be different for each button?
No i did not. Ok, i got it right now. But how would i display each button next to each other then if it reaches the end of the form, start displaying the buttons below the first?
you need to use a Form layout!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.