Home and Learn: C# NET Course

Adding C# Code To A Button

What we want to do now is to display a message box whenever the button is clicked. So we need the coding window. To see the code for the button, double click the button you added to the Form. When you do, the coding window will open, and your cursor will be flashing inside of the button code. It will look like this:

The C# code for a button

The only difference from the last time you saw this screen is the addition of the code for the button. This code:

private void button1_Click(object sender, EventArgs e)


This is just another Method, a piece of code that does something. The name of the Method is button1_Click. It's called button1 because that's currently the Name of the button. When you changed the Text, Location, and Size properties of the button, you could have also changed the Name property from button1 (the default Name) to something else.

The _Click part after button1 is called an Event. Other events are MouseDown, LocationChanged, TextChanged, and lots more. You'll learn more about Events later.

After _Click, and in between a pair of round brackets, we have this:

object sender, EventArgs e

These two are know as arguments. One arguments is called sender, and the other is called e. Again, you'll learn more about arguments later, so don't worry about them for now.

Notice that there is a pair of curly brackets for the button code:

private void button1_Click(object sender, EventArgs e)


If you want to write code for a button, it needs to go between the two curly brackets. We'll add a single line of code in the next part below.

back to the c# net contents page


Buy the Book of this Course

Email us: enquiry at homeandlearn.co.uk