How to Create and Use Buttons in C#

Buttons in C# WPF(Windows platform) and WFA(Web Form Applications)

Buttons are an essential part of any application whether it is desktop or web based. Now the Question is how to create buttons in C# and how to use them and perform some events on buttons click events.

Create a button in C#

First thing is that by using Visual Studio you have to simply drag and drop buttons from the toolbox. And visual studio also provides a wide range of button properties in GUI mode so that it less your programming efforts and it’s easy to put buttons of different styles and size on web pages and windows forms.

So First to put a button on design area we have to drag it from toolbox if tool box on the visual studio is not activated then click on View or press alt+I and select tool box from it .(It’s same for both platforms).

toolbox in visual studio
toolbox in visual studio

Button Properties

The built in provided properties is shown on the right side of the window. if they are not shown right click on a button and select properties:

properties in visual studio
properties in a visual studio

You can change any property of button interface from here like text, text color, font size background color, text-align etc.

Now if we want to perform some action when user click on the button so to code this simply double click on the button and the C# code file is open with .cs extension and there is a ready-made function same the name you put for the button like:

Now code here what we want when the user clicks on the button. This time, I want when user click button a message box pop up and say hello world.

Now C# code is :

this click button handler can also be generated by double click on the button in the visual panel. I just placed a message box int the button handler i.e.

Running Button

If we run the code and click on the button it will show a popup dialog box.

message box on button click
message box on button click

if I want to change the text, color, and width of button using c# then the code is:

coloured button in c# windows form
colored button in c# windows form

So as the above we change the properties of the button using the console or also by using C# code.

Button in ASP.NET

Now take a loop on buttons in Web pages (.aspx). In Web Forms we have some more advantages one is we manually create the buttons using asp button format which is:

Or simply drag it from the toolbox. Other is we apply styles on it using CSS. And the code for all changes is same as in windows palette form.

Leave a Reply

Your email address will not be published. Required fields are marked *