2017-06-08 32 views
0

我有一个数据网格视图和检查列表框。检查列表框是从数据库项目填充我想创建过滤器使用选中列表框的项目意味着通过检查选中列表框的项目填充数据网格视图现在的问题是数据网格视图只显示一个记录对应于选中项目但不显示多个记录如果多个复选框项被选中。如何通过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(); 

     } 

回答

0

首先,该项目名称的字符串被错误地组成,假设你有这些元素:当你想

OneTwoThree 

One 
Two 
Three 

你CONCAT会做

'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); 
+0

太谢谢你了!我感谢您的帮助 – owais

0

看来你的for循环符连接列表项。尝试写

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

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