ASP.NET - Button Control

The Button control is a commonly used control in ASP.NET that represents a button that the user can click to perform an action. Here are some of the basic events, methods, and properties of the Button control:

Events:

  • Click: This event is raised when the button is clicked by the user. You can handle this event to perform an action or run some code in response to the button being clicked.

Methods:

  • ToString: This method returns a string that represents the current Button control.
  • Focus: This method sets input focus to the Button control.
  • OnClick: This method programmatically simulates a button click event.

Properties:

  • Text: This property gets or sets the text displayed on the button.
  • Enabled: This property gets or sets a value indicating whether the button is enabled or disabled.
  • CssClass: This property gets or sets the CSS class that is applied to the button control.

 

In this example, the Button control has an ID of "Button1" and is set to run on the server. It displays the text "Click me" on the button. The OnClick attribute is set to "Button1_Click", which is the name of the method that will be executed when the button is clicked.

protected void Button1_Click(object sender, EventArgs e)
{
    // Code to handle the button click event goes here
}

In the above code, we have defined the btnSubmit_Click event handler, which will be called when the button is clicked. You can add your code to handle the button click event inside this method.

Let's say you want to create a simple web page that allows the user to enter their name in a text box and then displays a message when they click a button. Here are the steps you can follow:

Example

  • Open Visual Studio and create a new ASP.NET Web Forms project.
  • Drag and drop a TextBox control and a Button control from the Toolbox onto the page.
  • Set the ID property of the TextBox to "txtName" and the Text property of the Button to "Click Me".
  • Double-click on the Button control to create an event handler for the Click event.
  • In the code behind file, add the following code to the event handler:
protected void btnClickMe_Click(object sender, EventArgs e)
{
    string name = txtName.Text;
    string message = "Hello " + name + "! Welcome to ASP.NET.";
    lblMessage.Text = message;
}
  • Add a Label control to the page and set its ID property to "lblMessage".
  • Save and run the application.
  • Enter your name in the text box and click the button. You should see a message appear below the button that says "Hello [your name]! Welcome to ASP.NET."