Wednesday, 20 July 2011

Add Events to Controls Programmatically with ASP4.0 C#


This tutorial will demonstrate how to programmatically add events to controls on an ASP.NET page using C#.

Adding the Default.aspx Page
To demonstrate adding controls through the code behind, we will need to create a simple page that contains a button to which we can add events to. At this point, I have created a new ASP.NET Empty Web Site. To begin:
  1. Right click the project in your solution explorer.
  2. Select add new item...
  3. Select a web form.
  4. Name it ' Default.aspx'.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a button onto the web form.
We stand behind Server Intellect and their support team. They offer dedicated servers , and they are now offering cloud hosting

Adding the Event
Once we have our page setup, it is time to add some C# to the code behind to add an event to the button. To do this open up Default.aspx.cs for editing. Add in the following code to the Page_Load event method:
protected void Page_Load(object sender, EventArgs e)
{
    Button1.Click += new EventHandler(Button1_Click);
}

If you're ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.

What this has done is added an event handler to the button that we added earlier. In the event that the button is clicked, it will run the Button1_Click event method. Next, we need actually add the event method. To do this, add the following method to the Default.aspx.cs class under the Page_Load method:
protected void Button1_Click(object sender, EventArgs e)
{
    Button1.Text = "Event Fired!";
}

Notice that this method's signature corresponds to the event that it is being associated with, containing a sender object and event arguments. In different cases, you may need to have different types of event arguments. Here I am simply going to change the text property of the button when this method is called so we can easily test this.

Yes, it is possible to find a good web host. Sometimes it takes a while to find one you are comfortable with. After trying several, we went with Server Intellect and have been very happy thus far. They are by far the most professional, customer service friendly and technically knowledgeable host we've found so far.

Testing
To test this out, go ahead and load up the web site. When you click the button, the text should change from 'Button' to 'Event Fired!'. This confirms that our event method has actually executed. Adding events to controls programmitcally can be extremely useful when you have a dynamic set of controls that are not being defined within your '.aspx' file, but still need event handling.

No comments:

Post a Comment