Reputation: 57
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>");
}
Upvotes: 1
Views: 482
Reputation: 549
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.
Upvotes: 0
Reputation: 1607
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>");
}
Upvotes: 1
Reputation: 46
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
Upvotes: 0