0

在我正在处理的项目中,我的一些动态复选框有问题。

我有一个表格,在每行一个单元格中,我有一个复选框。选中此复选框以“标记”该记录。在用户设置了一系列过滤器后,单击按钮即可填充表中的记录。因此,表内容在每次回发时都会完全改变。

我使用一个列表来保存哪些记录已被标记,这样如果出现以前检查过的记录,也会在该检索时检查它。

我正在对我的page_load函数中的列表执行此检查,我可以通过调试看到它设置正确。但是,当页面加载完成时,检查的状态通常是错误的。

我是否需要将复选框状态验证步骤移至页面生命周期的另一部分?

任何提示都会很棒。我发现了一些关于带有复选框的 asp.net 问题的问题,但它们似乎与我的问题无关。

这是代码,请随时批评任何/全部:)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ScienceAssessmentToolASP
{
    public partial class createnewtest : System.Web.UI.Page
    {
    private int n;
    private SqlConnection conn = null;
    private List<int> flaggedQuestions = new List<int>();

    protected void Page_Load(object sender, EventArgs e)
    {

        if (IsPostBack)
        {
            var temp = (List<int>)Session["flaggedQuestions"];
            if (temp != null)
                flaggedQuestions = temp; ;//retrieve flags from session
            try
            {
                GetConn();
                ExecuteRetrieval();

                n = 1;
            }
            catch (Exception ex) { n = 0; Response.Write("for debugging: " + ex); }
            finally { if (conn != null) conn.Close(); }
            if (n < 0)
                //Label1.Text = "Connection Successful";
                Label3.Text = "Failed to Connect to Database, please contact the administrator.";
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {  
    }

    private void GetConn()
    {
        string connString = @"laalalala";


        conn = new SqlConnection(connString);
        conn.Open();
    }

    private void ExecuteRetrieval()
    {
        SqlDataReader reader = null;
        string query;

        if (!IsPostBack)
        {
            query = "select * from [ScienceQA]";
            flaggedQuestions = (List<int>)Session["flaggedQuestions"];//retrieve flags from session
        }
        else query = "select * from [ScienceQA] where [GradeLevel] = " + DropDownList1.Text +
            " and [Topic] = '" + DropDownList2.Text + "';";

        SqlCommand cmd = new SqlCommand(query, conn);

        reader = cmd.ExecuteReader();

        TableHeaderRow headerRow = new TableHeaderRow();
        TableHeaderCell idH = new TableHeaderCell();
        TableHeaderCell questionH = new TableHeaderCell();
        TableHeaderCell answerH = new TableHeaderCell();
        TableHeaderCell flagH = new TableHeaderCell();

        idH.Text = "ID";
        questionH.Text = "Question";
        answerH.Text = "Answer";
        flagH.Text = "Flag";

        headerRow.Cells.Add(idH);
        headerRow.Cells.Add(questionH);
        headerRow.Cells.Add(answerH);
        headerRow.Cells.Add(flagH);
        resultTable.Controls.Add(headerRow);

        while (reader.Read())
        {
            TableRow row = new TableRow();
            TableCell idCell = new TableCell();
            TableCell qCell = new TableCell();
            TableCell aCell = new TableCell();
            TableCell flag = new TableCell();

            idCell.Text = reader[0].ToString();
            qCell.Text = reader[1].ToString();
            aCell.Text = reader[2].ToString();

            CheckBox flagBox = new CheckBox();
            int id = Convert.ToInt32(idCell.Text);
            flagBox.AutoPostBack = true;
            flagBox.CheckedChanged += new System.EventHandler(flagButton_Click);
            flagBox.EnableViewState = true;
            flagBox.ViewStateMode = ViewStateMode.Enabled;

            if (flaggedQuestions.Contains(id) && flagBox.ID == "flag" + id)
                flagBox.Checked = true;
            else flagBox.Checked = false;

            flagBox.Text = id.ToString();
            flag.Controls.Add(flagBox);

            row.Cells.Add(idCell);
            row.Cells.Add(qCell);
            row.Cells.Add(aCell);
            row.Cells.Add(flag);
            resultTable.Controls.Add(row);          
        }

        Label4.Visible = true;
        flagCounter.Visible = true;
        resultTable.Visible = true;
    }


    protected void flagButton_Click(object sender, EventArgs e) 
    {
        CheckBox lb = (CheckBox)sender;
        int questionID = Convert.ToInt32(lb.ID.Substring(4));


        if (lb.Checked && !flaggedQuestions.Contains(questionID))  
        {
            //lb.Checked = false;
            flaggedQuestions.Add(questionID);
            flagCounter.Text = Convert.ToString(flaggedQuestions.Count);
        }
        else
        {
            //lb.Checked = true;
            flaggedQuestions.Remove(questionID);
            flagCounter.Text = Convert.ToString(flaggedQuestions.Count);
        }
        Session["flaggedQuestions"] = flaggedQuestions;//store questions to session
    }

    protected void createTestButton_Click(object sender, EventArgs e)
    {
        //create a test
        bool sendQuery = true;
        string author = Session["user"].ToString();
        string accessLevel = accessDropdown.Text;
        int gradeLevel = Convert.ToInt32(DropDownList1.Text);
        int questionCount = flaggedQuestions.Count();
        string testType = testTypeDropDown.Text;
        string description = descriptionBox.Text;

        string questionString = "";

        for (int i = 0; i < flaggedQuestions.Count(); i++)
            questionString += flaggedQuestions[i] + ",";

        string query = @"Insert into Tests Values ('" + author + "','" + questionString
             + "','" + accessLevel + "','" + gradeLevel + "','" + questionCount + "','"
              + testType + "','" + description +"');";

        //check parameters
        if (accessLevel == "")
        {
            errorLabel.Text = "Please choose an access level.";
            sendQuery = false;
        }
        if (questionCount == 0)
        {
            errorLabel.Text = "Please flag a set of questions before creating a test.";
            sendQuery = false;
        }
        if (testType == "")
        {
            errorLabel.Text = "Please choose a test type";
            sendQuery = false;
        }
        if (description == "")
        {
            errorLabel.Text = "Please describe your test";
            sendQuery = false;
        }
        if (sendQuery)
        {

            try
            {
                GetConn();
                SqlCommand cmd = new SqlCommand(query, conn);
                cmd.Prepare();
                int n; 
                n = cmd.ExecuteNonQuery();
            }
            catch (Exception e2) { n = 0; }

            if (n == 1)
                errorLabel.Text = "Test Created Successfully";
            else errorLabel.Text = "Test Creation Failed, please check your parameters.";
        }
    }

}
}

这是对我有用的解决方案,将复选框状态检查移至 onprerender 函数。

        protected override void OnPreRender(EventArgs e)
    {
        foreach (TableRow row in resultTable.Rows)
        {
            var cell = row.Cells[3];
            foreach (Control control in cell.Controls)
            {
                var flagBox = control as CheckBox;
                if (flagBox != null)
                {
                    int id = Convert.ToInt32(flagBox.ID.Substring(4));
                    if (flaggedQuestions.Contains(id) && flagBox.ID == "flag" + id)
                        flagBox.Checked = true;
                    else flagBox.Checked = false;
                }
            }
        }
    }
4

1 回答 1

1

您可能需要更新 PreRender 中复选框的选中状态,因为这发生在按钮单击事件触发之后。

于 2012-11-28T21:49:27.137 回答