1

I created a simple asp button using code behind. I added this button on page successfully and it is showing me on web page but I got a problem when I clicked on the button then after post back the button hide on web page. please help me to resolve this. Here is my code :

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        CreateButton();
    }
}
protected void CreateButton()
{
    Button btn = new Button();
    btn.ID = "newDynamicBtn";
    btn.Text = "Click Me";
    //btn.Attributes.Add("runat", "server");
    //btn.Attributes.Add("onClick", "newDynamicBtn_Click");
    //btn.OnClientClick = "return confirm('are you sure ?')";
    btn.Click += newDynamicBtn_Click;
    form1.Controls.Add(btn);
}
protected void newDynamicBtn_Click(object sender, EventArgs e)
{
    Response.Write(@"<script>alert('Hello')</script>");
}
2
  • 2
    CreateButton method isn't called when it is a PostBack. Take it outside of that if condition and then it will work Commented Mar 3, 2016 at 7:35
  • I removed the if condition on page load. Thanks @VishnuPrasad Commented Mar 3, 2016 at 8:11

3 Answers 3

1

Every time when button call it also runs Page_Load event, if you want button display every time then you have to make function

CreateButton() without any condition of (!postBack)

Example

protected void Page_Load(object sender, EventArgs e)
{
        CreateButton();
}


protected void CreateButton()
{
    Button btn = new Button();
    btn.ID = "newDynamicBtn";
    btn.Text = "Click Me";
    //btn.Attributes.Add("runat", "server");
    //btn.Attributes.Add("onClick", "newDynamicBtn_Click");
    //btn.OnClientClick = "return confirm('are you sure ?')";
    btn.Click += newDynamicBtn_Click;
    form1.Controls.Add(btn);
}
protected void newDynamicBtn_Click(object sender, EventArgs e)
{
    Response.Write(@"<script>alert('Hello')</script>");
}
Sign up to request clarification or add additional context in comments.

Comments

0

As Vishnu Prasad said in a comment, your code is only creating the button the first time the page loads because of the condition if(!isPostBack). You just have to remove that condition if you want your button to appear in the page after a post back

Comments

0
if(!IsPostBack)

Purpose of above code is to check if the page is requested for the first time or not. If the page is requested for the first time then the code inside the if condition gets execute otherwise no. That is why you are not seeing the button second time.

call createButton() outside the if condition.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.