Monday, September 20, 2010

Creating Dynamic buttons using C#

protected void Page_Load(object sender, EventArgs e)
{
Button myButton = null;

//Create 5 button dynamically
for (int i = 0; i < 5; i++)
{
//Create new instance of Button class and assign it necessary property
myButton = new Button();
myButton.ID = "myButton" + i; //Assign Id
myButton.Text = "myButton" + i;

//Attach the button click event handler
myButton.Click += new EventHandler(myButton_Click);

//Add Newly created Button to Panel
pnlButton.Controls.Add(myButton);

//Add berek so the next Button will create in next new line
Literal lit = new Literal();
lit.Text = "

";
// add the Button to panel in a web page
pnlButton.Controls.Add(lit);

}
}
void myButton_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if(btn !=null)
{
Response.Write("Button id " + btn.ID + " clicked");
}
}

No comments:

Post a Comment