News & UpdatesProgrammingWeb programming Store My Projects
Links
Affiliates

ASP.NET Tutorial – 09 – Events II

Continuing from the last section, let’s say you didn’t want to use the button to update the label, but instead have the text box do so automatically. The first step then is to add a TextChanged event to the TextBox.

<asp:TextBox ID="myTextBox" 
             runat="server"
             OnTextChanged="myTextBox_TextChanged"></asp:TextBox>

Next, in the event handler, update the button label to the content of the text box.

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

Postback

If you try the application now the label won’t update. This highlights an important point: for a server-side event to occur a postback to the server must take place, so that the server can process the event and send a new page to the user. The only controls that automatically trigger a postback are the three web button controls – Button, LinkButton, and ImageButton. For the other controls you need to explicitly set the AutoPostBack property to “true” to achieve this result.

<asp:TextBox ID="myTextBox" 
             runat="server" 
             AutoPostBack="True" 
             OnTextChanged="myTextBox_TextChanged"></asp:TextBox>

Running the application this time will cause the text box to fire a postback that updates the button. Note that this happens only when the user leaves the control, not while changing it. Every time a postback such as this occurs, the Page_Load event handler will execute. To stop this method from running code on a post back, you can check the IsPostBack property of the Page control. If it is “false” the page is loaded for the first time.

protected void Page_Load(object sender, EventArgs e)
{
  if(Page.IsPostBack == false)
    myTextBox.Text = "";
}

HTML control events

HTML controls can also use events similar to the web controls, but Visual Studio won’t give much support in adding them. In design view they won’t show up in the properties window and in source view all of the events belonging to the Document Object Model (DOM) will show up on Intellisense, even those that can’t be added to the referenced control.

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