Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

Stivan Radev
Stivan Radev
1,475 Points

Invisible Button(Problem) in Microsoft Visual Studio

So I'm trying to create a button when the Form1 Loads but for some reason the button is not visible, please help!

Here is my code:

private void Form1_Load(object sender, EventArgs e)
        {
            Button b = new Button();
            b.Visible = true;
            b.Text = "TEST";
            b.Location = new Point(15, 15);

        }

1 Answer

First of all, you also need to specify a height and a width. After that you also need to add the button to the controls. The following should work in your example:

private void Form1_Load(object sender, EventArgs e)
{
    Button b = new Button();

    b.Visible = true;
    b.Text = "TEST";
    b.Location = new Point(15, 15);
    b.Height = 20;
    b.Width = 100;

    Controls.Add(b);
}

A documentation on how to add controls to windows forms can be found here: https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-add-controls-to-windows-forms

Stivan Radev
Stivan Radev
1,475 Points

Thank you so much !!!!