1

In my ASP.NET web application I have a form submit with checkboxes.

If in the first option 2 or 3 are selected, then a new questionnaire opens with 7 more questions. It's necessary to select all fields to navigate to next one.

    protected void btnNextSDGSection2_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(rblSDG1Question1.SelectedValue))
        {
            lblMessageSection3.Text = "<br />⚠ Please select an option for Q1 before proceeding.";
            lblMessageSection3.ForeColor = System.Drawing.Color.Red;
            return;
        }

        int recordId = (int)Session["companyProfileID"];
        string selectedOption = rblSDG1Question1.SelectedValue;

        string query= @"
            SELECT COUNT(*) 
            FROM sdgAlignmentSurvey_Section2 
            WHERE sdgAlignmentSurvey_Section2ID = @id";

        using (SqlConnection conn = SqlConnectionClass.GetConnection())
        {
            conn.Open();

            using (SqlCommand cmd = new SqlCommand(query, conn))
            {
                cmd.Parameters.AddWithValue("@id", recordId);

                int exists = (int)cmd.ExecuteScalar();

                if (selectedOption == "0" || selectedOption == "1")
                {
                    if (exists > 0)
                    {
                        string queryUpdate = @"
                        UPDATE sdgAlignmentSurvey_Section2 
                        SET Q1 = @option 
                        WHERE sdgAlignmentSurvey_Section2ID = @id";

                        using (SqlCommand cmdUpdate = new SqlCommand(queryUpdate, conn))
                        {
                            cmdUpdate.Parameters.AddWithValue("@option", selectedOption);
                            cmdUpdate.Parameters.AddWithValue("@id", recordId);
                            cmdUpdate.ExecuteNonQuery();

                            lblMessageSection3.Text = $"<br />✅The option '{selectedOption}' is updated successfully.";
                            lblMessageSection3.ForeColor = System.Drawing.Color.Green;
                        }
                    }
                    else
                    {
                        string queryInsert = @"
                        INSERT INTO sdgAlignmentSurvey_Section2 (sdgAlignmentSurvey_Section2ID, Q1)
                        VALUES (@id, @option)";

                        new SqlCommand("SET IDENTITY_INSERT sdgAlignmentSurvey_Section2 ON", conn).ExecuteNonQuery();

                        using (SqlCommand cmdInsert = new SqlCommand(queryInsert, conn))
                        {
                            cmdInsert.Parameters.AddWithValue("@id", recordId);
                            cmdInsert.Parameters.AddWithValue("@option", selectedOption);
                            cmdInsert.ExecuteNonQuery();

                            lblMessageSection3.Text = $"<br />✅The option '{selectedOption}' is inserted successfully.";
                            lblMessageSection3.ForeColor = System.Drawing.Color.Green;
                        }

                        new SqlCommand("SET IDENTITY_INSERT sdgAlignmentSurvey_Section2 OFF", conn).ExecuteNonQuery();
                    }
                }
            }

            bool allValid = true;

            if (selectedOption == "2" || selectedOption == "3")
            {
                var checkboxes = new[] {
                    CheckBoxList1, CheckBoxList2, CheckBoxList3,
                    CheckBoxList4, CheckBoxList5, CheckBoxList6, CheckBoxList7
                };

                foreach (var list in checkboxes)
                {
                    if (string.IsNullOrEmpty(list.SelectedValue))
                    {
                        allValid = false;
                        break;
                    }
                }

                if (allValid)
                {
                    SaveRelatedOptions(recordId, selectedOption);
                }
                else
                {
                    lblMessageSection3.Text = "<br />⚠ Please select an option in all sub-questions before proceeding.";
                    lblMessageSection3.ForeColor = System.Drawing.Color.Red;
                }
            }
            else
            {
                string queryDelete = "DELETE FROM sdgAlignmentSurvey_Section2_q1_options WHERE FK_companyProfileID = @recordId";
                using (SqlCommand cmdDelete = new SqlCommand(queryDelete, conn))
                {
                    cmdDelete.Parameters.AddWithValue("@recordId", recordId);
                    cmdDelete.ExecuteNonQuery();
                }
            }            
        
            Session["SDG_Q1_Answer"] = selectedOption;

            if (allValid)
            {
                ((Pages.SDG_Alignment_Flow.SDG_Alignment_Genel)this.Page).NextStep();
            }
        }
    }

This code works properly and saves the selected options to the database as expected.

When all checkboxes are not selected, an error is displayed to select all, but the issue is that all the selected ones are reset to null.

How should I modify it so that the selected options do not reset and after the error (for missing checkboxes) I can see already the selected ones on page postback?

I have no related part in my if (Page.IsPostBack == false) part.

As well, I have a function to load saved question answers from the database as follows:

private void LoadQ1Answer()
{
    using (SqlConnection conn = SqlConnectionClass.GetConnection())
    {
        conn.Open();

        int recordId = (int)Session["companyProfileID"];

        string query = @"
            SELECT Q1 
            FROM sdgAlignmentSurvey_Section2 
            WHERE sdgAlignmentSurvey_Section2ID = @id";

        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
            cmd.Parameters.AddWithValue("@id", recordId);

            object result = cmd.ExecuteScalar();

            if (result != null && result != DBNull.Value)
            {
                string savedOption = result.ToString();
                ListItem item = rblSDG1Question1.Items.FindByValue(savedOption);

                if (item != null)
                {
                    rblSDG1Question1.ClearSelection();
                    item.Selected = true;

                    if (savedOption == "2" || savedOption == "3")
                    {
                        pnlSDG1ExtraMessage.Visible = true;
                        LoadQ1Details(recordId, savedOption);
                    }
                    else
                    {
                        pnlSDG1ExtraMessage.Visible = false;
                    }

                    lblMessageSection2.Text = $"Selected: {item.Text}";
                }
            }
        }
    }
}

This function, is out of if (Page.IsPostBack == false) so the question answers are always loaded from the database and if I place that inside if (Page.IsPostBack == false) the results are not displayed at all.

0

1 Answer 1

0

Well, the code that loads up the controls on FIRST page load should MOST certainly go inside of the if (!IsPostBack) {code here }. The reason is page load fires first each EVERY time a post back occurs, and fires BEFORE a given event stub for button/controls on the form. And in place of 7 hard coded check boxes, use a CheckBoxList which can be re-loaded and feed from code/database. Selecting check boxes and post-backs DO NOT re-set check boxes - YOUR code in doing that! So, place first page load and setup code in the page load !IsPostBack block. Additional code free to change checkboxes with additional button clicks (and events for controls). However, as noted, page load event will fire over and over, and fires each post-back, and fires BEFORE say a button click event. So, in theory you REALLY want to use a "real first page load", and the way you do this with web forms?

You use this:

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // code here to FIRST page load to setup and load up controls 
                // and setup your page
            }
        }

So keep in mind that page load fires EACH time a post-back occurres. That means if you place "setup" code in the page load event, it going to run each and every time a button click or post-back occurres. After page load event, then your button or control code event runs. So, this is why you MUST use the !IsPostBack code block in your page load even to to FIRST setup your controls. If that code is not placed in the page load if (!IsPostBack) code block, then it will run each and every time - thus causing your controls to be re-set and the code "setup" code for that given page will run each and every time

In fact, you really can't build a proper working Webforms page without using the !IsPostBack code block, and the last 250+ web pages I created in asp.net WebForms? They all had a !IsPostBack code stub in the page load event.

Sign up to request clarification or add additional context in comments.

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.