News & UpdatesProgrammingWeb programming Store My Projects
Links
Affiliates

ASP.NET Tutorial – 08 – Events I

Generic events

All controls in ASP.NET can register events. To find which events a control has available, add and select the control in design view and switch over to “Events” in the properties window. At the bottom of the list under “Misc” there are five events that can be trigged for different parts of the control’s life cycle: Disposed, Init, Load, PreRender, and Unload. Above these is the DataBinding event, which occurs when the server control binds to a data source, such as a database. Each of these six events exists for all web controls.

Control specific Events

For the most part however, the event you will want to use is the top most one, under the “Action” tab. For example, the Button control has the “Click” event, the TextBox has the “TextChanged” event, the CheckBox has the “CheckedChanged” event, and so on. Some controls, such as the label, have no action events at all.

Example

In the example below there are two web controls on the page, a Button and a TextBox.

<asp:Button ID="myButton" 
            runat="server" 
            Text="Button" />
 
<asp:TextBox ID="myTextBox" 
             runat="server"></asp:TextBox>

Registering an Event

To register a Click event for the button, go to its event list and position the caret to the right of the Click event. If you want, you can type a name for the event handler here, but you can also leave it blank to let Visual Studio generate the name. To create the event handler hit the return key here. An alternative way of creating the event is to simply double-click on the button, since Click is the default event for this control. Either way, when you register the event Visual Studio will take you to the code page where it has created an empty event handler for you to use.

protected void myButton_Click(object sender, EventArgs e)
{
 
}

The default method name consists of the control’s ID and the event type, which is a good naming convention to follow. If you look at the ASPX file in source view (View->Markup), you can also see that the “OnClick” property has been added to the button control. This is what links the button to the event handler in the code file.

<asp:Button ID="myButton" 
            runat="server" 
            Text="Button" 
            OnClick="myButton_Click" />

Go back to the code page and add code to the event handler so that when the button is clicked its label is changed to the text contained in the TextBox control.

protected void myButton_Click(object sender, EventArgs e)
{
  myButton.Text = myTextBox.Text;
}

If you try the application now, you can see that clicking the button indeed changes its label to the content of the text box.

Recommended additional reading:
Sams - Teach Yourself ASP.NET 3.5 in 24 Hours