如何登记由checkedlistbox过滤的多个记录

时间:2017-06-08 01:18:23

标签: c# datagridview checkedlistbox

我有一个数据网格视图和选中的列表框。检查列表框是从数据库项填充我希望创建过滤器使用选中列表框的项目意味着通过选中检查列表框的项目填充数据网格视图现在问题是数据网格视图只显示一个记录对应于选中的项目,但如果选中多个复选框项目,则不显示多个记录。

enter image description here

        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = @"Data Source=DESKTOP-50ME4GC\SQLEXPRESS;Initial Catalog=autolab;Integrated Security=True";
        if (pn.CheckedItems.Count != 0)
        {
            // If so, loop through all checked items and print results.  
            string s = "";
            int x;
            for (x = 0; x <= pn.CheckedItems.Count - 1; x++)
            {
                s = s + pn.CheckedItems[x].ToString();
            }
            connection.Open();
            SqlCommand cmd = new SqlCommand("SELECT *  from test_report  inner join tests  on test_report.test_name = tests.Test_name WHERE tests.Test_name IN ('" + s + "') ", connection);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);


            DataTable tbl = new DataTable();


           adapter.Fill(tbl);


            dt.DataSource = tbl;


            connection.Close();

        }

2 个答案:

答案 0 :(得分:0)

似乎你的for循环连接列表项。试着写

s = s + pn.CheckedItems[x].ToString() + ", ";

不要忘记在循环后删除最后一个“,”。

答案 1 :(得分:0)

首先,带有项目名称的字符串组成不正确,假设您有这些元素:

One
Two
Three

你的联合会这样做:

OneTwoThree

虽然你想要:

'One','Two','Three'

所以你需要像这样纠正concat:

        string s = "";
        int x;
        for (x = 0; x <= pn.CheckedItems.Count - 1; x++)
        {
            s = s + "'" + pn.CheckedItems[x].ToString() + "',";
        }

        s = s.Substring(0, s.Length - 1);

并将查询更正为:

SqlCommand cmd = new SqlCommand("SELECT *  from test_report  inner join tests  on test_report.test_name = tests.Test_name WHERE tests.Test_name IN (" + s + ") ", connection);