Hi Azhar,
I found that whatever controls are created Dynamically, needs to be created each time the page loded, Your first button is working fine because its in Page load and being created every time page loaded.
SOLUTION:
You need to do the way I done in the following article.....
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
.CS
TableRow row;
TableCell cell;
private List<Button> DynamicControls
{
get { return Session["DynamicControls"] != null ? (List<Button>)Session["DynamicControls"] : null; }
set { Session["DynamicControls"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
Button txt = new Button();
txt.Width = Unit.Pixel(169);
txt.Height = Unit.Pixel(26);
txt.Text = "Text1";
txt.ID = "CreateButton";
txt.Click += new EventHandler(CreateButton);
//txt.OnClientClick = "ButtonClick(this)";
row = new TableRow();
cell = new TableCell();
cell.Controls.Add(txt);
row.Controls.Add(cell);
Panel1.Controls.Add(row);
if (this.IsPostBack)
{
this.ReloadDynamicControls();
}
else
{
DynamicControls = new List<Button>();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Button t = new Button();
row = new TableRow();
cell = new TableCell();
cell.Controls.Add(t);
row.Controls.Add(cell);
// Button t = new Button();
t.Width = Unit.Pixel(129);
t.Height = Unit.Pixel(26);
//t.Text = GridView1.Rows[i].Cells[0].Text;
t.Text = "Button_" + this.DynamicControls.Count.ToString();
//t.ID = GridView1.Rows[i].Cells[0].Text;
t.ID = "btn_" + this.DynamicControls.Count.ToString();
t.Click += new EventHandler(Button2_Click);
t.EnableViewState = true;
//t.OnClientClick = "Button2Click(this)";
Panel1.Controls.Add(row);
DynamicControls.Add(t);
}
protected void CreateButton(object sender, EventArgs e)
{
Button t = new Button();
row = new TableRow();
cell = new TableCell();
cell.Controls.Add(t);
row.Controls.Add(cell);
// Button t = new Button();
t.Width = Unit.Pixel(129);
t.Height = Unit.Pixel(26);
//t.Text = GridView1.Rows[i].Cells[0].Text;
t.Text = "Button2";
//t.ID = GridView1.Rows[i].Cells[0].Text;
t.ID = "btn_" + this.DynamicControls.Count.ToString();
t.Click += new EventHandler(Button2_Click);
t.EnableViewState = true;
//t.OnClientClick = "Button2Click(this)";
Panel1.Controls.Add(row);
DynamicControls.Add(t);
}
private void ReloadDynamicControls()
{
if (this.DynamicControls != null)
{
foreach (Button button in DynamicControls)
{
button.Click += new EventHandler(Button2_Click);
row = new TableRow();
cell = new TableCell();
cell.Controls.Add(button);
row.Controls.Add(cell);
Panel1.Controls.Add(row);
}
}
}
RECOMMANDATION : Please try this thng on a fresh page, Dont direcly just paste on your existing page. On a fresh page look how this thing is working and then only you can merge it to the your existing page.
Thanks and Regards,
Rk_Hirpara