How to Add Events to the Dynamically Created Control in ASP.NET WebForm?
Here I will explain how to add events to the controls which will be create dynamically in your asp.net web application using C#. That means adding a control dynamically to the web form and assaigning events to the newly created control in your WebForm/WebPage.
Sometimes we need to dynamically add some controls in our web page in page load or
something else and we need to assign some events to these controls. This code
snippet will help you how to do that.
Here I am adding a Button Control to the WebForm in Page_load Event. And also
adding a Click Event to this Button to do some work.
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Creating New Control..
Button SubmitBtn = new Button();
// Adding Control to the WebForm..
Form.Controls.Add(SubmitBtn);
// Changing Value of Property of the Control..
SubmitBtn.Text = "Submit";
// Adding Event to the Control..
SubmitBtn.Click += SubmitBtn_Click;
}
protected void SubmitBtn_Click(object sender, EventArgs e)
{
Response.Write("Fired!!!");
}
}