Wednesday, June 24, 2009

Dynamic controls in asp.net, Adding a dynamic control to a placeholder control and wire up the event in ASP.net

ASP.NET provides a dedicated control the PlaceHolder control. You can place this control somewhere on your webform and later on use it to hang dynamic controls.

Now i am describing step by step how i generate and use LinkButton Dynamically.
Refer below code to generate Linkbutton at runtime.

Step 1-First take placeholder on your webform

Step 2-write this code on server side in c#


protected override void OnInit(EventArgs e)
{
for(int i=0;i<5;i++)
{

LinkButton LinkToEditPage = new LinkButton();

LinkToEditPage.Text = "Name" + i.ToString();
//Add new LinkButton to placeholder
PlaceHolder1.Controls.Add(LinkToEditPage);
LinkToEditPage.Attributes.Add("IdUser", "LinkButton" + i.ToString());
// Wire up the eventhandler
LinkToEditPage.Click += new EventHandler(LinkToEditPage_Click);
}
}


//its Event handler code below

protected void LinkToEditPage_Click(object sender, EventArgs e)
{
// Get the control and cast it to the
// appropriate type. In our case a LinkButton.

LinkButton LB = (LinkButton)sender;
string IdUser = LB.Attributes["IdUser"];

Response.Write("You Click on " + IdUser);

}

Step 3-see the output:

when you will run this webform, output will be show like refer below.


when you click on any of one output message will come accordingly.
suppose you have click on secod linkButton output will come as
"You Click on LinkButton2"

I hope this example can give you the idea how to generate dynamic control in asp.net and handle their event.

No comments:

Post a Comment