检查依赖复选框列表C#中的多个选项

时间:2014-04-07 17:21:57

标签: c# sql checkboxlist

我从sql查询生成一个CheckBoxList,并且一切正常,CheckBoxList是依赖的,因此,当我检查一个唯一选项时,它会生成另一个CheckBoxList,它也可以正常工作。我想检查多个选项并获取所有数据,但查询仅在检查了最后一个chekbox时运行。

如何实现接受CheckBoxList中检查的所有选项并显示所有数据的查询?

这是我的代码:

protected void cblList1_SelectedIndexChanged(object sender, EventArgs e)
{
    foreach (ListItem list1 in cblList1.Items)
    {
        if (list1 .Selected == true)
        {
            LoadCheckBoxListList2(list1);
        }
    }
}

private void LoadCheckBoxListList2(ListItem itemList1)
{
    SqlCommand cmd = new SqlCommand("SELECT DISTINCT tbl_information.route AS ROUTE FROM tbl_information INNER JOIN tbl_regional ON tbl_information.region = tbl_regional.id_regional WHERE tbl_information.supervisor = " + "'" + itemList1 + "'", conn);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);

    cblRutas.DataSource = ds;
    cblRutas.DataValueField = "ROUTE";
    cblRutas.DataBind();
}

3 个答案:

答案 0 :(得分:0)

      for (int i = 0; i < checkedListBox1.Items.Count; i++)
        {
            if (checkedListBox1.GetItemChecked(i))
            {
                string str = (string)checkedListBox1.Items[i];
                //Do your function call here
            }
        }

答案 1 :(得分:0)

如果我的问题正确无误,那么在SelectedIndexChanged事件处理程序中,您必须收集所有已检查项目的列表(不仅是最后一项)和查询中没有where id=@id过滤但{{{ 1}}。

所以你只需稍微改变你的代码:

where id in (@id1, @id2, etc)

答案 2 :(得分:0)

我得到了答案,这是代码:

protected void cblList1_SelectedIndexChanged(object sender, EventArgs e)
{
    List<string> list1 = new List<string>();
    foreach (ListItem itemList1 in cblList1.Items)
    {
        if (itemList1 .Selected == true)
        {
            list1.Add(itemList1.Text)
        }
    }
    LoadCheckBoxListList2(list1);
}

private void LoadCheckBoxListList2(List<string> list1)
{
    DataTable dt = new DataTable("R");
    dt.Columns.Add("Route", typeof(string));

        foreach (string li in list1)
        {
            string query = @"SELECT DISTINCT tbl_information.route AS ROUTE FROM tbl_information INNER JOIN tbl_regional ON tbl_information.region = tbl_regional.id_regional WHERE tbl_information.supervisor = '" + li + "'";

            SqlCommand cmd = new SqlCommand(query, conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            bool b = false;

            foreach (DataRow item in ds.Tables[0].Rows)
            {
                if (!b)
                {
                    dt.Rows.Add(item[0] + " (" + li + ")");
                    b = true;
                    continue;
                }

                dt.Rows.Add(item.ItemArray);
            }
        }

        cblRutas.DataSource = dt;
        cblRutas.DataValueField = "ROUTE";
        cblRutas.DataBind();
    }

谢谢你的aswers !!!