Different Windows Controls | Button | C# | BKNMU Junagadh



In C#, the Button class is part of the Windows Forms framework and is used to create a button control in a graphical user interface (GUI) application. Buttons are often used to trigger actions when clicked. Here are some common methods and properties associated with the Button class:
Properties:
Name:
  • Gets or sets the name of the control.
  • Example: button1.Name = "btnSubmit";
Text:
  • Gets or sets the text that is displayed on the button.
  • Example: button1.Text = "Click Me";
Enabled:
  • Gets or sets a value indicating whether the button is enabled.
  • Example: button1.Enabled = true;
Visible:
  • Gets or sets a value indicating whether the button is visible.
  • Example: button1.Visible = false;
BackColor:
  • Gets or sets the background color of the button.
  • Example: button1.BackColor = Color.Blue;
ForeColor:
  • Gets or sets the foreground color (text color) of the button.
  • Example: button1.ForeColor = Color.White;
Size:
  • Gets or sets the size of the button.
  • Example: button1.Size = new Size(100, 30);
Location:
  • Gets or sets the location of the button.
  • Example: button1.Location = new Point(50, 50);
Methods:
Click:
  • Simulates a click on the button, triggering the Click event.
  • Example: button1.PerformClick();
Focus:
  • Sets input focus to the button.
  • Example: button1.Focus();
ToString:
  • Returns a string that represents the current object.
  • Example: string buttonInfo = button1.ToString();

Event:
  1. Click Event:
Occurs when the button is clicked.
Example:
private void button1_Click(object sender, EventArgs e)
{
// Code to execute when the button is clicked
}
You can attach the event handler in the code-behind or in the designer.
Example Usage: using System;
using System.Windows.Forms; namespace ButtonExample
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Button Clicked!");
} private void MainForm_Load(object sender, EventArgs e)
{
// Set properties during form load
button1.Text = "Click Me";
button1.BackColor = System.Drawing.Color.Blue;
button1.ForeColor = System.Drawing.Color.White;
button1.Size = new System.Drawing.Size(100, 30);
button1.Location = new System.Drawing.Point(50, 50);
}
}
}
In this example, the button1_Click method handles the button click event. Properties like Text, BackColor, ForeColor, Size, and Location are set in the MainForm_Load event handler during form initialization.

Post a Comment

Thanks for comment.

Previous Post Next Post