Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Postback on button ASP.NET c#

Tags:

c#

asp.net

here is an example of what I am doing

Page Load
{
   //Adds items to a panel (not an updatepanel just a normal panel control)
}

 protected void btnNexMod_Click(object sender, EventArgs e)
{

   // Calls DoWork() and Appends more items to the same panel
}

My problem is that the asp:button is doing a postback as well as calling DoWork()

Therefore, re-calling my page load, re-initializing my panel :(

I want my items that I have added to the panel to stay there!

All help appreciated, not looking for a hand you the answer kind-of deal. Any steps are appreciated thanks!

Here is an exact example of my problem.

protected void Page_Load(object sender, EventArgs e)
{

    CheckBox chkbox = new CheckBox();
    chkbox.Text = "hey";
    chkbox.ID = "chk" + "hey";

    // Add our checkbox to the panel
    Panel1.Controls.Add(chkbox);
}
protected void Button1_Click(object sender, EventArgs e)
{
    CheckBox chkbox = new CheckBox();
    chkbox.Text = "hey";
    chkbox.ID = "chk" + "hey";

    // Add our checkbox to the panel
    Panel1.Controls.Add(chkbox);
}

Only thing on the page is a empty panel and a button with this click even handler.

I have also tried this and it still doesn't work. Now its clearing the initial item appended to the panel.

if (!Page.IsPostBack) // to avoid reloading your control on postback
{

    CheckBox chkbox = new CheckBox();
    chkbox.Text = "Initial";
    chkbox.ID = "chk" + "Initial";

    // Add our checkbox to the panel
    Panel1.Controls.Add(chkbox);
}
like image 499
clamchoda Avatar asked Nov 02 '11 19:11

clamchoda


2 Answers

If you're adding controls to the Panel dynamically, then you'll have to recreate the controls at every postback, and make sure to assign the same IDs to the controls so that ViewState can populate the values. It's usually best to recreate dynamic content during OnInit, but this can be difficult in some situations.

One of my favorite tools is the DynamicControlsPlaceHolder, because you can add dynamic controls to it and it will persist them automagically, without any additional coding required on the page. Just add controls to it, and it will do the rest.

Here's the link:
http://www.denisbauer.com/Home/DynamicControlsPlaceholder

As for preventing your button from performing a postback, use OnClientClick and return false.

OnClientClick="return false;"
like image 195
James Johnson Avatar answered Oct 09 '22 08:10

James Johnson


You could use

<asp:LinkButton OnClientClick="javascript:addItemsToPanel();return false;" 

thus using a javascript function to add them. That's how I've got around that problem.

like image 4
poldoj Avatar answered Oct 09 '22 08:10

poldoj