Adding Controls to Windows Form at Runtime C#

This is a basic introduction on how to add a control to a windows form using C#. In this example we will add a button to a form with an On Click event.

Firstly let’s add the button with the following code. You can add this to the Load event of the form to create automatically when the form loads:

    Button btn = new Button();
    btn.Name = 'btnNew';
    btn.Left = 100;
    btn.Top = 100;
    btn.Text = 'New Button';
    Controls.Add(btn);

Running the form shows that we have created a button object by giving it a name and some text, and specified it’s position on the form (distance from the Left and Top in pixels), and then adding the button to the Controls collection on the form. You could set lots of other properties as required, e.g. Enabled, Visible, TextAlign, etc.

This is okay, other than a button without an On Click event is not much use. So we’ll add a bit of code that will show the Name of the button when it’s clicked.

    private void btn_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        MessageBox.Show(btn.Name);
    }

We now have some code to execute when the button is clicked (this takes the sender object, allocates it to a Button object then shows the name of the passed button).

Now we need to associate this code with the On Click event of the button. To do this need to add the following line of code before the Controls.Add(btn).

    btn.Click += new EventHandler(btn_Click);

This adds btn_Click function to the btn.Click event, so our completed code looks like this:

    Button btn = new Button();
    btn.Name = 'btnNew';
    btn.Left = 100;
    btn.Top = 100;
    btn.Text = 'New Button';
    btn.Click += new EventHandler(btn_Click);
    Controls.Add(btn);

Now if you run the form the button is created when the form loads and clicking on the created button should show a message box displaying “New Button” (the name of our created button).

Advertisements
This entry was posted in Programming and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s