C#嵌套的foreach循环 - CheckBoxList

时间:2014-07-17 18:02:30

标签: c# sql-server foreach nested

我有两个checkBoxLists,一个名为CheckBoxList1(3个项目,让我们称之为A,B和C),另一个是CheckBoxList2(包含2个项目,我们称之为1和2)。

我将从checkboxlist1和checkboxlist2中选择的值插入到数据库中的两列,但是我遇到了这个问题:当我选择例如A和B然后是1和2时,这是导入到的值数据库:

column1  column2
A        1, 2
B        1, 2, 1, 2

我想:

column1  column2
A        1, 2
B        1, 2

这是我的尝试:

using (var command = new SqlCommand(query, conn))
{
    string Optional = "";

    foreach (var item in CheckBoxList1.Items.Cast<ListItem>().Where(item => item.Selected))
    {
        command.Parameters.Clear();
        command.Parameters.AddWithValue("@planName", item.Text);

        foreach (var item1 in CheckBoxList2.Items.Cast<ListItem>().Where(item1 => item1.Selected))
        {
            {
                Optional = Optional + item1.Text;
            }

        }
        command.Parameters.AddWithValue("@optionPlan", Optional);
        command.ExecuteNonQuery();
    }
}

1 个答案:

答案 0 :(得分:3)

在进入内部循环之前,将Optional变量重置为string.Empty

using (var command = new SqlCommand(query, conn))
{

    foreach (var item in CheckBoxList1.Items.Cast<ListItem>().Where(item => item.Selected))
    {
        command.Parameters.Clear();
        command.Parameters.AddWithValue("@planName", item.Text);

        // If you don't reset the Optional here the next loop on CheckBoxList1 add
        // to the current value of Optional giving an invelid string
        string Optional = "";
        foreach (var item1 in CheckBoxList2.Items.Cast<ListItem>().Where(item1 => item1.Selected))
        {
                Optional = Optional + item1.Text;
        }
        command.Parameters.AddWithValue("@optionPlan", Optional);
        command.ExecuteNonQuery();
    }
}