Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

Handling events for programmatically created WebControls in ASP.NET

Author: Usman Lateef

In this article you will learn how to hook up events and handle events for programmatically created WebControls.

In previous article of Programmatically adding WebControls to web page you have learned how to add WebControls to a web page at run time. When you have created WebControls the next step is to wire up their events.
 
Note: If you don’t know how to add WebControls on web page at run time, please refer to my other article “Programmatically adding WebControls to a web page”.
 
When creating controls you wire up events with them as in Page_Load or OnInit event of the Web Page, but remember to do it in the same event where you added controls on the web page:
 
C#
 
myButton.Click += new EventHandler(myButton_Click);
 
VB.NET
 
AddHandler myButton.Click, AddressOf myButton_Click
 
 
Write following event handler method in code behind file. If you are attaching one event handler method to more than one control of same type, then sender parameter is used to know which control fire up that event. For example:
 
C#
 
protected void myButton_Click(object sender, EventArgs e) {
 
  Button myButton = (Button)sender;
  myLabel.Text = myButton.Text + " was Clicked";
 
}
 
VB.NET
 
Private Sub myButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles myButton.Click
 
  Dim myButton As Button = CType(sender, Button)
  myLabel.Text = myButton.Text + " was Clicked"
 
End Sub
 
Other events like “Text_Changed” for TextBox control can be wire up and handled in the same way.
   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< Programmatically adding WebControls to Web Page in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net