搜索所选复选框值

时间:2013-12-10 06:39:12

标签: c# asp.net .net asp.net-mvc c#-4.0

我有一个带复选框列表的下拉列表。当我选择项目并尝试通过单击搜索按钮在网格中显示时,我无法做到这一点。

protected void btnSearchEmpCode_Click(object sender, EventArgs e)
    {
        string selectedValues = string.Empty;
        foreach (ListItem item in cblEmpCode.Items)
        {
            if (item.Selected)
                selectedValues += "'" + item.Value + "',";
        }
        if (selectedValues != string.Empty)
            selectedValues = selectedValues.Remove(selectedValues.Length - 1);
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("SELECT *FROM Details WHERE Emp_Code IN (" + selectedValues + ")", con);
        SqlDataAdapter Adpt = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        Adpt.Fill(dt);
        AIGrids.DataSource = dt;
        AIGrids.DataBind();
    }

如果我在某处出错,任何人都可以纠正我。

2 个答案:

答案 0 :(得分:0)

第一件事:

确保

中的*From之间存在差距
"SELECT *FROM Details WHERE Emp_Code IN (" + selectedValues + ")"

第二,确保查询未形成为:

"SELECT *FROM Details WHERE Emp_Code IN (val1,val2,)"

(最后用逗号保留。)

应该形成如下:

"SELECT *FROM Details WHERE Emp_Code IN (val1,val2)"

答案 1 :(得分:0)

问题1:您要将'单引号添加到Emp_Code列。
问题2:您未在space*之间提供FROM

试试这个:

protected void btnSearchEmpCode_Click(object sender, EventArgs e)
{
    string selectedValues = string.Empty;
    foreach (ListItem item in cblEmpCode.Items)
    {
        if (item.Selected)
            selectedValues +=  item.Value + ",";
    }

    if (selectedValues != string.Empty)
        selectedValues = selectedValues.Remove(selectedValues.Length - 1);
    SqlConnection con = new SqlConnection(strcon);
    SqlCommand cmd = new SqlCommand("SELECT * FROM Details WHERE Emp_Code IN (" + selectedValues + ")", con);
    SqlDataAdapter Adpt = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    Adpt.Fill(dt);
    AIGrids.DataSource = dt;
    AIGrids.DataBind();
}