无法搜索所选项目

时间:2014-03-17 10:10:52

标签: asp.net .net

我正在使用此代码搜索复选框列表中的所选项目,但它无法正常工作。

protected void btnSearchCode_Click(object sender, ImageClickEventArgs e)
{
    string selectedValues = string.Empty;
    foreach (ListItem item in cblCode.Items)
    {
        if (item.Selected)
            selectedValues += item.Value + ",";
    }
    if (selectedValues != string.Empty)
        selectedValues = selectedValues.Remove(selectedValues.Length - 1);
    cblCode.DataSource = DataReport.SearchCode(selectedValues);
    cblCode.DataBind();
} 

 public static DataTable SearchCode(string selectedValues)
    {
        string strcon = ConfigurationManager.ConnectionStrings["LocalDB"].ConnectionString;
        DataTable datatable = new DataTable();
        using (SqlConnection conn = new SqlConnection(strcon))
        {
            conn.Open();
            SqlCommand command = new SqlCommand();
            string strQuery = "Select Group, Name from Details where Code in (" + selectedValues + ")", conn;
            command.Connection = conn;
            SqlDataAdapter dataadapter = new SqlDataAdapter();
            dataadapter.SelectCommand = command;
            DataSet ds = new DataSet();
            dataadapter.Fill(datatable);
        }
        return datatable;
    } 

真的很感激任何帮助。

3 个答案:

答案 0 :(得分:1)

你根本没有使用过strQuery。

试试这个:

public static DataTable SearchCode(string selectedValues)
      {
        string strcon = ConfigurationManager.ConnectionStrings["LocalDB"].ConnectionString;
        DataTable datatable = new DataTable();
        using (SqlConnection conn = new SqlConnection(strcon))
        {
            conn.Open();

            string strQuery = "Select Group, Name from Details where Code in (" + selectedValues + ")";
            SqlCommand command = new SqlCommand(strQuery, conn);
            SqlDataAdapter dataadapter = new SqlDataAdapter();
            dataadapter.SelectCommand = command;
            DataSet ds = new DataSet();
            dataadapter.Fill(datatable);
        }
        return datatable;
    } 

答案 1 :(得分:0)

将参数传递到数据库时始终使用SqlParamerter

我认为您缺少单个引号,因为您的SeletedValues为string

string strQuery = "Select Group, Name from Details 
where Code in ('" + selectedValues + "')", conn;

答案 2 :(得分:0)

您创建了查询字符串,但从未将其分配给command变量。因此,当您将其分配给selectCommand时,无法从DB查询任何内容。您想添加此行代码以将查询字符串分配给变量: command = new SqlCommand(strQuery,conn);