dangtis dangtis - 3 months ago 30
ASP.NET (C#) Question

Cant uncheck checkbox. ASP.NET

Problem most likely is with the QueryString. Everything falls apart when I go back from results page to search page. I use the QueryString to check all boxes that were checked before the results page is generated. This time I can uncheck checked boxes, but only visually. The results page will be generated as if they were still checked.

Here is simple example of it. I have added checkbox and a button...

protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["B1"] != null)
{
CheckBox1.Checked = true;
}
}

protected void Button1_Click(object sender, EventArgs e)
{
string QString = null;
if (CheckBox1.Checked)
{
QString += "?B1=1";
}
Response.Redirect("/TestPage1.aspx" + QString);
}


If I go to Default.aspx and if I add "?B1=1"(Default.aspx?B1=1) I get page where checkbox is checked. If I uncheck it and press Button1, I will be redirected to page "TestPage1.aspx?B1=1"

Does anyone have a solution to this problem?

Answer

If I understand correctly, you are on TestPage1 with the checkbox checked (/TestPage1.aspx?B1=1) and when you manually uncheck the checkbox and click Button1 you return to /TestPage1.aspx?B1=1 and the checkbox is now rechecked.

This is occurring because the Page_Load event is raised before control events such as the OnClick event of Button1. Here is the MSDN documentation detailing the page lifecycle events.

Since your page is posting back to the /TestPage1.aspx?B1=1, the Page_Load handler sees the query string before the Button1_Click has a chance to remove it. By the time the Button1_Click handler runs, the checkbox has already been rechecked and the handler redirects back to the same url, query string included.

A simple solution for your example would be to to check the IsPostBack property in your Page_Load event and only check the checkbox if the page is not posting back.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack && Request.QueryString["B1"] != null)
    {
        CheckBox1.Checked = true;
    }
}
Comments