Dynamic Button control with click event not working in ASP.Net using C#

Last Reply on Feb 28, 2018 03:25 AM By kalpesh

Posted on Feb 28, 2018 02:26 AM
hi developers ,
 
i am created a dynamic control in asp:Panel. its fine. i want to change the label number in each click of the dynamic created button. when if i clicking the dynamic control button the first click is working well , but the second click its not working , but the third click is working well.its working like a even method. so i need to click twice a button. 
 
so how can i solve this problem . i have done all but this is the only and major issue in my module.
below am adding all of my codes . all of you go through and if anyone know the solution to my problem please suggest me to how can i done this task.
 
Html aspx Page Code 
<asp:Panel runat="server" ID="pnl_btns" CssClass="exm-btn"></asp:Panel>
<asp:Button ID="btnLoadButton" runat="server" Text="Button" Visible="false" OnClick="btnLoadButton_Click"></asp:Button>
<asp:Label ID="lbl" runat="server" ForeColor="Red" Font-Size="Larger"></asp:Label>
 
C# Code Behind Page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
if (IsPostBack)
{
bind();
}
}
protected void btnLoadButton_Click(object sender, EventArgs e)
{
pnl_btns.Controls.Clear();
string text = (sender as Button).Text;
 
if (text == "1")
{
lbl.Text = text;
lbl.ForeColor = Color.Green;
}
else if (text == "2")
{
lbl.Text = text;
lbl.ForeColor = Color.Red;
}
else
{
lbl.Text = text;
lbl.ForeColor = Color.Yellow;
}
bind();
}
public void bind()
{
for (int i = 0; i < 5; i++)
{
Button btn = new Button();
btn.Text = "" + (i + 1);
btn.Click += btnLoadButton_Click;
pnl_btns.Controls.Add(btn);
}
}
 
thanking you
Paul.S
Posted on Feb 28, 2018 03:25 AM

Assign Id for the DynamicButton And Same way assign it from code behid.

C#

protected void Page_Load(object sender, EventArgs e)
{
    bind("btn");
} 
protected void btnLoadButton_Click(object sender, EventArgs e)
{
    pnl_btns.Controls.Clear();
    string text = (sender as Button).Text;
    if (text == "1")
    {
        lbl.Text = text;
        lbl.ForeColor = Color.Green;
    }
    else if (text == "2")
    {
        lbl.Text = text;
        lbl.ForeColor = Color.Red;
    }
    else
    {
        lbl.Text = text;
        lbl.ForeColor = Color.Yellow;
    }
    bind("btn");
}
    
public void bind(string prefix)
{
    for (int i = 0; i < 5; i++)
    {
        Button btn = new Button();
        btn.ID = prefix + (i + 1);
        btn.Text = "" + (i + 1);
        btn.Click += btnLoadButton_Click;
        pnl_btns.Controls.Add(btn);
    }
}

Screenshot