复选框值存储和插入多次

时间:2018-04-16 10:46:54

标签: c# checkbox

我有一个程序需要注册问题。一个问题可以有1个或多个正确答案,如方法checkTaskType()中所述。 所有整数都在代码的开头声明。 代码运行正常并且有效,问题是如果我想在不关闭表单的情况下注册多个问题,则来自previouse复选框的值将在下一个问题上注册为正确答案。

- 不要介意数据库设计,这是一个临时解决方案

    //Method for insert to DB
    private void InsertQAData()
    {
        using (var con = new MySqlConnection(_connectionString))
        {
            con.Open();
            MySqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText =
                @"INSERT INTO task(tasktext, alt_1, alt_2, alt_3, alt_4, alt_5, illustration_link, task_type, alt_1_correct, alt_2_correct, alt_3_correct, alt_4_correct, alt_5_correct)
            VALUES (@taskText, @alt_1, @alt_2, @alt_3, @alt_4, @alt_5, @illustration_link, @taskType, @corrAlt1, @corrAlt2, @corrAlt3, @corrAlt4, @corrAlt5);";
            cmd.Parameters.AddWithValue("@taskText", txtQuestion.Text);
            cmd.Parameters.AddWithValue("@alt_1", txtAlt_1.Text);
            cmd.Parameters.AddWithValue("@alt_2", txtAlt_2.Text);
            cmd.Parameters.AddWithValue("@alt_3", txtAlt_3.Text);
            cmd.Parameters.AddWithValue("@alt_4", txtAlt_4.Text);
            cmd.Parameters.AddWithValue("@alt_5", txtAlt_5.Text);
            cmd.Parameters.AddWithValue("@illustration_link", txtLink.Text);
            cmd.Parameters.AddWithValue("@taskType", taskType);
            cmd.Parameters.AddWithValue("@corrAlt1", corrAlt1);
            cmd.Parameters.AddWithValue("@corrAlt2", corrAlt2);
            cmd.Parameters.AddWithValue("@corrAlt3", corrAlt3);
            cmd.Parameters.AddWithValue("@corrAlt4", corrAlt4);
            cmd.Parameters.AddWithValue("@corrAlt5", corrAlt5);
            DataTable dt = new DataTable();
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            da.Fill(dt);
            lblInserted.Show();
      }

    // Method for checking if a question has 1 or multiple answers
    private void checkTaskType()
    {
        if (checkBox1.Checked)
        {
            count += 1;
            corrAlt1 = 1;
        }
        if (checkBox2.Checked)
        {
            count += 1;
            corrAlt2 = 1;
        }
        if (checkBox3.Checked)
        {
            count += 1;
            corrAlt3 = 1;
        }
        if (checkBox4.Checked)
        {
            count += 1;
            corrAlt4 = 1;
        }
        if (checkBox5.Checked)
        {
            count += 1;
            corrAlt5 = 1;
        }
        if (count == 1)
        {
            taskType = "oneAlternative";
        }
        if (count > 1)
        {
            taskType = "multipleAlternatives";
        }
    }

1 个答案:

答案 0 :(得分:1)

致电checkTaskType()后调用方法ClearResult(),如:

private void ClearResult()
{
count  = 0;
corrAlt1 = 0;
corrAlt2 = 0;
corrAlt3 = 0;
corrAlt4 = 0;
corrAlt5 = 0;
taskType = string.Empty;
}

这将在填写并存储到DB的问题后帮助您,将varibles重新初始化为默认状态。

所以

checkTaskType();
//fill DB with values
//...
ClearResult();