Create Button at runtime (2009-09-03)
Taking System.Web.UI.WebControls.Button as a testing Control
Creating Button control dynamically and adding on the Form following way and assign Click event to it,
Code in the Page_Load method will be called every time the Form Post
btn_Click method will be executed whenever the Dynamically created Button clicked.
protected void Page_Load(object sender, EventArgs e) { int x = 0; int y =100; for (int i = 1; i < 10; i++) { Button btn = new Button(); btn.Name = "btn" + i.ToString(); btn.Text = "Button " + i.ToString(); btn.Click += new EventHandler(btn_Click); btn.Location = new Point(x, y); y += 30; this.Controls.Add(btn); } }
void btn_Click(object sender, EventArgs e) { int btnIndex = Convert.ToInt32(((Button)sender).ID.Substring(3, 1)); Response.Write(btnIndex.ToString()); }
|