Last Updated :
25 Mar, 2025
A Button is an essential part of an application, software, or webpage. .NET Framework, the Button class is used to represent Windows button control and it is inherited from the ButtonBase class. It is defined under System.Windows.Forms namespace.
It allows users to interact with applications. Clicking an exit button closes the app, for example. Buttons enable actions like submitting or downloading, varying in appearance and reusable across programs.
Ways to Create a Button in Windows Forms
There are mainly two ways to create a button in Windows forms which are mentioned below.
- Drag and drop (Design-Time)
- Custom Button (Run-Time)
Drag and drop (Design-Time)
This is the easiest way to create a button in Windows Forms using Visual Studio we just have to open the toolbox and drag and drop the button on the form in the designer and further we can change the appearance of the button using the properties. Follow these steps to create a button.
Step 1: Locate the project in Visual Studio. In this example, we are using the default project name, Form1. Open the form in the editor to modify it further.
In the image, we have two files that are open one Design and there is Form1.cs these two play a major role. We use the Form 1.cs file for the custom logic.
Step 2: Now open a Toolbox go to the view > Toolbox or ctrl + alt + x.
Step 3. Now open the Common Controls section, then drag and drop a button onto the form where you want it to be placed.
Step 4. Now open the properties of the button press right-click on the button and it will open the properties solution explorer now we can change the button name to Click here.
Now we are changing the Text property from button1 to Click Here.
Step 5: We can change the appearance and the behaviour of the button using the properties.
Output:
Custom Button (Run-Time)
In this method we are going to modify the Form1.cs file and add custom code modification in C# to change the appearance of the button according to our requirements. Follow these step by step process.
Step 1: Create a button using the Button() constructor provided by the Button class.
// Creating Button using Button class
Button MyButton = new Button();
Step 2: After creating the Button, set the properties of the Button provided by the Button class.
// Set the location of the button
Mybutton.Location = new Point(225, 198);
// Set text inside the button
Mybutton.Text = “Submit”;
// Set the AutoSize property of the button
Mybutton.AutoSize = true;
// Set the background color of the button
Mybutton.BackColor = Color.LightBlue;
// Set the padding of the button
Mybutton.Padding = new Padding(6);
// Set font of the text present in the button
Mybutton.Font = new Font(“French Script MT”, 18);
Step 3: And last add this button control to form using the Add() method.
// Add this Button to form
this.Controls.Add(Mybutton);
Step 4: Now double-click on the button in Design and it will open the Form cs file where code is written in C#. Here the program file is Form 1.cs Now write this code in Form1.cs file
Form1.cs file:
C#
namespace WinFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = "Do you want to submit this project?"; l.Location = new Point(222, 145); l.Font = new Font("French Script MT", 18); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = "Submit"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); Mybutton.Font = new Font("French Script MT", 18); // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(360, 198); Mybutton1.Text = "Cancel"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); Mybutton1.Font = new Font("French Script MT", 18); // Adding this button to form this.Controls.Add(Mybutton1); } private void button1_Click(object sender, EventArgs e) { } } }
Output:
Properties of Button
These are the important properties of the button
Property | Description |
---|---|
BackColor | Using the BackColor property you can set the background color of the button. |
BackgroundImage | Using the BackgroundImage property you can set the background image on the button. |
AutoEllipsis | Using the AutoEllipsis property you can set a value shows that whether the ellipsis character (…) appears at the right edge of the control which denotes that the button text extends beyond the specified length of the button. |
AutoSize | Using AutoSize property you can set a value which shows whether the button resizes based on its contents. |
Enabled | Using Enabled property you can set a value which shows whether the button can respond to user interaction. |
Events | Using the Events property you can get the list of the event handlers that are applied on the given button. |
Font | Using Font property you can set the font of the button. |
FontHeight | Using FontHeight property you can set the height of the font. |
ForeColor | Using the ForeColor property you can set the foreground color of the button. |
Height | Using the Height property you can set the height of the button. |
Image | Using Image property you can set the image on the button. |
Margin | Using the Margin property you can set the margin between controls. |
Name | Using Name property you can set the name of the button. |
Padding | Using the Padding property you can set the padding within the button. |
Visible | Using the Visible property you can set a value which shows whether the button and all its child buttons are displayed. |
Events on Button
Event | Description |
---|---|
Click | This event occurs when the button is clicked. |
DoubleClick | This event occurs when the user performs a double click on the button. |
Enter | This event occurs when the control is entered. |
KeyPress | This event occurs when the character, or space, or backspace key is pressed while the control has focus. |
Leave | This event occur when the input focus leaves the control. |
MouseClick | This event occurs when you click the mouse pointer on the button. |
MouseDoubleClick | This event occurs when you double-click the mouse pointer on the button. |
MouseHover | This event occurs when the mouse pointer is placed on the button. |
MouseLeave | This event occur when the mouse pointer leaves the button. |
In C#, creating a button is a fundamental aspect of building graphical user interfaces. Buttons are essential for user interaction and performing actions. In this guide, we will walk through the process of creating a button in C# step by step.
1. Creating a Button in a Windows Form Application
To create a button in a Windows Form application, you can follow these simple steps:
using System;
using System.Windows.Forms;
namespace ButtonExample
{
public class ButtonForm : Form
{
public ButtonForm()
{
Button myButton = new Button();
myButton.Text = "Click Me";
myButton.Location = new System.Drawing.Point(50, 50);
this.Controls.Add(myButton);
}
static void Main()
{
Application.Run(new ButtonForm());
}
}
}
In this example, we create a simple form with a button that says «Click Me» at position (50, 50) on the form.
2. Handling Button Click Events
Handling button click events allows you to define what happens when a user clicks on the button. Here’s how you can handle a button click event in C#:
myButton.Click += (sender, e) =>
{
MessageBox.Show("Button Clicked!");
};
In this code snippet, a message box will display with the text «Button Clicked!» when the button is clicked.
3. Customizing Button Properties
You can customize various properties of a button such as color, size, font, and more to suit your application’s design. Here’s an example of changing the button’s background color:
myButton.BackColor = System.Drawing.Color.Blue;
Feel free to explore and experiment with different properties to create buttons that match your application’s style.
By following these steps and examples, you can easily create buttons in C# for your Windows Form applications. Buttons are essential components for user interaction and adding functionality to your applications.
This C# tutorial uses the Button control from Windows Forms. A Button can be clicked.
Button. A button accepts clicks.
In Windows Forms we use a Button control that accepts click events and performs other actions in the user interface. This control provides a way to accept input—and invoke logic based on that input.
Start. First, this tutorial uses the Windows Forms control set. The Button control is one control you can add to any Windows Forms program. It renders as a rectangular box with text or images in the center.
Action: You can use a Button control to perform an action when the user clicks or presses a key to activate the button.
Event
Add. Let’s describe how you can add a Button control to a Windows Forms program. In Visual Studio, make sure the Window you want to add the button to is shown. Go to the View menu and select the Toolbox option.
This presents a list of all the Windows Forms controls you can add to your project on the screen. Locate the Button item in the Toolbox window and either double-click it or drag it to your window.
And: Now, when you see the Button on the window that was inserted, you can right-click on it and select Properties.
Text. In the properties pane or window, you can either change the regular properties or the event handlers on the Button control. You can alter any Button property through the properties window.
Next: We see how the Button properties were changed so that the Button contains the text «Open» instead of the «button1» default label.
Using ellipsis (three periods). Here we use three periods after the Text property on the Button control in the properties window. We use three periods (an ellipsis) because the Button in our example will be used to open a dialog window.
The ellipsis is used to signal that an action that requires the user’s attention such as a dialog box will occur if the control is activated as by clicking on it. I feel that using ellipses correctly on strings in programs is important.
Click. Windows Forms programs are event-based. They are idle until the user takes an action upon a control. When you add a Click event handler to a Button, the event handler method will be invoked when the user clicks on the button.
Note: Windows Forms provides some automatic features that will turn an Enter keypress into a Click event in some cases.
In the Visual Studio properties window, a lightning bolt signifies the event handlers list. You can click on it and then double-click on an event. At that point, the C# code will be inserted into the user-code portion of the project.
Then: You manually edit that C# code to add the program-specific logic. Any statements can be used.
Instead of double-clicking to create a new event handler for one control event, you can use the drop-down box to select a method that already exists to handle the events. There are restrictions: the method signature must be compatible.
Tip: Wiring multiple events to one event handler is useful. It can simplify the source code of medium-complexity programs.
Windows Forms code that uses Button control: C# using System; using System.Windows.Forms; namespace WindowsFormsApplication21 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { MessageBox.Show("Dot Net Perls says hello.", "How is your day going?"); } } }
We see the body of the Click event that can be added to handle click events for the button1 control instance. You do not need to manually type in the «button1_Click» method signature, and doing so is much harder to maintain.
Instead: You can the interface in Visual Studio to create empty event handler methods.
Then: You can insert logic such as calling the MessageBox.Show method call to perform a trivial action when the event is processed.
MessageBox.Show
Discussion. Let’s consider various tips and tricks you can use to enhance the Button functionality in your Windows Forms controls. Generally, by specifying the constraints of your Button, you can avoid modifying pixel dimensions for the most part.
Tip: You should experiment with the Anchor property to control the resizing of the Button if it is in a variable-sized window.
Further: I recommend putting Buttons inside TableLayoutPanel cells, as this reduces the need to position them manually.
TableLayoutPanel
Button Enabled property. You can at any time change the enabled state of buttons by setting Enabled to true or false. I recommend tying the Enable property’s value to an expression based on another part of the user interface.
Also: You can assign multiple Enabled properties on controls to each other to ensure the user interface is usable at all times.
Summary. We explored the Button control in the Windows Forms control set. First we created a new Windows Forms project. We added add a new instance of the Button control. We next changed the appearance of the Button control and its text.
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf
You currently have JavaScript disabled on your web browser.
This website uses JavaScript, and This web page needs JavaScript activated to work correctly.
Please active JavaScript on your web browser and then refresh this web page.
Button
By Tim-Bo Tolbert, posted on Dec 20, 2021
The Button control is found in the System.Windows.Forms
namespace within the System.Windows.Forms.dll
. In this blog post I am referring to the Button control that is available in C# .NET-Core (.NET 6.0) with Visual Studio 2022 (although this code example might still work OK with older .NET versions).
The purpose and function of a Button control is to provide the user with a measure of interaction capabilities with a program by allowing the user to click on the buttons surface area to trigger a callback click event. The Button control offers additional other events as a means of user interaction as well, other than the click event, but the click event is probably the most used event for this control.
The Button control can be found in the Controls Toolbox window panel within the Forms editor screen. The Button control is a graphical control which takes up some visible space (i.e. real estate) on the form. The position, size and shape of the Button control is variable, and can be set at design time by either through the programs source code or by setting the controls properties using the Form editors property window. The Button controls position, size, shape, and most other properties can also be set and altered at runtime through the programs source code.
A Button control can be clicked by using the mouse, Enter key, or Spacebar, if the button has focus.
To use a button control as a forms Accept or Cancel button, then set the AcceptButton or CancelButton property of the form to allow users to click the button by pressing the Enter (for Accept) or the ESC (for Cencel) keys, even if the button does not have focus. This gives the form the behavior of a dialog box.
When you use the ShowDialog method to display a form, you can specify the return value of that ShowDialog method by setting the DialogResult property of a button on that form.
Example Source Code
This example uses a Button control and a MessageBox object.
To add the Button control to your form, you can double click on its name (i.e. Button) as listed in the Toolbox window panel within the Form editor window. Alternatively, you can single click on it and then drag and drop it onto your form, to position it more closer to where you want it to be positioned at. Once it is added to the form then it will appear on the forms surface area having default button control values.
After you have added the button control to your form then once you select it then you can view and edit that button objects property values in the Properties window within the Forms editor window, where you can then change the buttons Name, Text, and other properties as you desire.
In the example below, I have added a button control object to my form, and then changed the Text property value to «Click Me» :
From the Form editor, double click on the button object that you just added to the Form. Doing so will automatically create and link a callback method to the buttons Click event into that forms .cs source code file, which you can then program some action to be performed whenever the button is clicked.
In the following example, when the program is running and someone clicks on the forms «Click Me» button, then a popup message box will display having the message «Hello» :
namespace TestProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//
}
private void button1_Click(object sender, EventArgs e)
{
// display a popup message box
MessageBox.Show("Hello");
}
}
}
Alternatively, you can also instantiate a new instance of the Button class object as a variable and then add it to the forms control collection manually within the programs source code. If you create and add the button manually within the programs source code instead of by drag and dropping the object in the Form editors window, then you will need to also set all of its properties and callback events manually as well. Below is an example source code of doing just that:
namespace TestProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// instantiate an instance of a new button
Button button1 = new Button();
// add the click event and tie it to a method
button1.Click += Button1_Click;
// set the buttons properties
button1.Name = "button1";
button1.Text = "Click Me";
button1.Left = 20;
button1.Top = 20;
// add the button to the form
this.Controls.Add(button1);
}
// the method to handle the buttons click event
private void Button1_Click(object? sender, EventArgs e)
{
// display a popup message box
MessageBox.Show("Hello");
}
}
}
When you run this example program and click on the «Click Me» button then you should see the following:
Final Thoughts
Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.
This page has been viewed a total of 2036 times.
кнопка
Кнопки являются одним из самых простых элементов управления и в основном используются для выполнения некоторого кода, когда пользователь хочет.
Здесь у нас действительно простой случай, показывается кнопка «Сообщение» при нажатии кнопки. Мы добавляем кнопку в форму, назовите ее cmdShowMessage
используется в коде, чтобы идентифицировать объект и установить текст кнопок для отображения сообщения.
Нам просто нужно дважды щелкнуть кнопку на визуальном дизайнере, а Visual Studio создаст код для события click. Теперь нам просто нужно добавить код для MessageBox:
private void cmdShowMessage_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello world!");
}
Если мы запустим программу сейчас и нажмите кнопку, мы увидим сообщение:
Текстовое окно
Текстовые поля позволяют пользователю вводить данные в программу.
Мы собираемся изменить форму и добавить текстовое поле, чтобы окно сообщения отображало нам сообщение, которое хочет пользователь. Теперь наша форма выглядит так:
Затем измените событие нажатия кнопки, чтобы использовать текст текстового поля:
private void cmdShowMessage_Click(object sender, EventArgs e)
{
string UserText = txtUserMessage.Text;
MessageBox.Show(UserText);
}
Как вы можете видеть , что мы используем .Text
свойство Textbox , что является текст , содержащийся в texbox.
Если мы запустим программу, мы сможем писать в текстовом поле. Когда мы нажимаем кнопку, MessageBox покажет текст, который мы написали:
Поле со списком
Комбобокс позволяет пользователю выбирать один из вариантов, предоставляемых разработчиком.
Мы собираемся изменить форму и добавить combobox, чтобы в окне сообщений отображалось сообщение, которое пользователь хочет из списка, который мы предоставим.
После добавления комбо в форму теперь добавим список опций в комбо. Для этого нам нужно изменить свойство Items
:
Теперь нам нужно изменить код события click:
private void cmdShowMessage_Click(object sender, EventArgs e)
{
string OptionText = cboSelectOption.SelectedItem.ToString();
MessageBox.Show(OptionText);
}
Как вы видите, мы используем свойство SelectedItem
, оно содержит объект выбранной опции. Поскольку нам нужна строка для показа, и компилятор не знает, является ли объект строкой или нет, нам нужно использовать метод ToString()
.
Если мы запустим программу, мы сможем выбрать тот вариант, который мы предпочитаем, и когда мы нажмем кнопку, появится окно сообщения:
Чтобы получать уведомление, когда пользователь выбирает элемент из поля со списком, используйте событие SelectionChangeCommitted
. Мы могли бы использовать событие SelectedIndexChanged
, но это также возникает, когда мы программным образом меняем элемент select в combobox.
CheckBox
Флажок — это элемент управления, который позволяет пользователю получать boolean
значения от пользователя по специальному вопросу типа «Все в порядке?». ,
Имеет событие под названием CheckedChanged
, которое происходит всякий раз, когда свойство check
изменяется.
Вот CheckBox, на который есть вопрос «Проверено?». ,
Мы получили этот MessageBox
из события CheckedChanged
,
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
bool IsChecked = checkBox1.Checked;
MessageBox.Show(IsChecked.ToString());
}
Если CheckBox IsChecked
переменная IsChecked
будет true
.
Если CheckBox не установлен — переменная IsChecked
будет false
.
ListBox
Listbox
— это элемент управления, который может содержать коллекцию объектов. Listbox
похож на Combobox
но в Combobox
; Только избранные элементы видны пользователю. В Listbox
; все элементы видны пользователю.
Как добавить элементы в ListBox?
private void Form3_Load(object sender, EventArgs e)
{
string test = "Trial";
string test2 = "45";
int numberTest = 43;
decimal decimalTest = 130;
listBox1.Items.Add(test);
listBox1.Items.Add(test2);
listBox1.Items.Add(numberTest);
listBox1.Items.Add(decimalTest);
}
Выход ;
Или могут быть предоставлены datasources
данных,
private void Form3_Load(object sender, EventArgs e)
{
List<string> TestList = new List<string> { "test1", "test2", "test3", "44", "55" };
listBox1.DataSource = TestList;
}
Выход;
private void Form3_Load(object sender, EventArgs e)
{
SqlConnection Connection = new SqlConnection("Server=serverName;Database=db;Trusted_Connection=True;"); //Connetion to MS-SQL(RDBMS)
Connection.Open(); //Connection open
SqlDataAdapter Adapter = new SqlDataAdapter("Select * From TestTable", Connection); // Get all records from TestTable.
DataTable DT = new DataTable();
Adapter.Fill(DT); // Fill records to DataTable.
listBox1.DataSource = DT; // DataTable is the datasource.
listBox1.ValueMember = "TestID";
listBox1.DisplayMember= "TestName";
}
Правильный вывод ;
Предоставление внешнего источника данных sql для listbox требуется, ValueMember
и DisplayMember
Если НЕ будет выглядеть так,
Полезные события;
SelectedIndex_Changed;
Определить список для предоставления источника данных
private void Form3_Load(object sender, EventArgs e)
{
List<string> DataList = new List<string> {"test1" , "test2" , "test3" , "44" , "45" };
listBox1.DataSource = TestList;
}
В дизайне формы выберите « Listbox
и нажмите F4, или с правой стороны щелкните значок подсветки.
Visual studio будет генерировать listBox1_SelectedIndexChanged
для codebehind.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int Index = listBox1.SelectedIndex;
label1.Text = Index.ToString();
}
Результат SelectedIndex_Changed
; (метка внизу показывает индекс каждого выбранного элемента)
SelectedValue_Changed; (Источник данных такой же, как и сверху, и вы можете сгенерировать это событие, например SelectedIndex_Changed)
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
label1.Text = listBox1.SelectedValue.ToString();
}
Выход ;
NumericUpDown
NumericUpDown — это элемент управления, который выглядит как TextBox. Этот элемент управления позволяет пользователю отображать / выбирать номер из диапазона. Стрелки вверх и вниз обновляют значение текстового поля.
Контроль выглядит;
В диапазоне Form_Load
можно установить.
private void Form3_Load(object sender, EventArgs e)
{
numericUpDown1.Maximum = 10;
numericUpDown1.Minimum = -10;
}
Выход;
UpDownAlign будет устанавливать положение стрелок;
private void Form3_Load(object sender, EventArgs e)
{
numericUpDown1.UpDownAlign = LeftRightAlignment.Left;
}
Выход;
UpButton()
увеличивает количество элементов управления. (можно вызывать из любого места. Я использовал button
чтобы позвонить).
private void button1_Click(object sender, EventArgs e)
{
numericUpDown1.UpButton();
}
**Выход
DownButton()
уменьшает количество элементов управления. (можно вызывать из любого места. Я использовал button
чтобы вызвать ее снова.)
private void button2_Click(object sender, EventArgs e)
{
numericUpDown1.DownButton();
}
Выход;
Полезные события
ValueChanged;
Это событие будет работать при нажатии стрелки вверх или вниз.
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
decimal result = numericUpDown1.Value; // it will get the current value
if (result == numericUpDown1.Maximum) // if value equals Maximum value that we set in Form_Load.
{
label1.Text = result.ToString() + " MAX!"; // it will add "MAX" at the end of the label
}
else if (result == numericUpDown1.Minimum) // if value equals Minimum value that we set in Form_Load.
{
label1.Text = result.ToString() + " MIN!"; // it will add "MIN" at the end of the label
}
else
{
label1.Text = result.ToString(); // If Not Max or Min, it will show only the number.
}
}
Выход ;