[英]Multiple selection on a checkboxlist to filter a datatable vb.net
hope you are doing fine. 希望你一切都好。
I have a datatable loaded from a database. 我有一个从数据库加载的数据表。 I bind the datatable to a gridview on page_load. 我将数据表绑定到page_load上的gridview。 Now I want to filter the gridview by a user selection so I made a checkboxlist and wrote some code as follow at CheckBoxList1_SelectedIndexChanged 现在,我想通过用户选择来过滤gridview,所以我创建了一个复选框列表,并在CheckBoxList1_SelectedIndexChanged中编写了一些代码,如下所示
Dim selectedartist As String = CheckBoxList1.SelectedItem.ToString()
Dim dTable As DataTable = Session("dTable")
Dim dTablenew As New DataTable
Dim str As String = "Song_Artist ='" & selectedartist & "'"
dTablenew = dTable.Select(str).CopyToDataTable
GridView1.DataSource = dTablenew
GridView1.DataBind()
With this code above, it can filter if there is only one selection on the checkboxlist. 有了上面的这段代码,它可以过滤复选框列表中是否只有一个选项。 I try to loop the checkboxlist myself but always ended up in errors. 我尝试自己循环检查清单,但总是以错误告终。 Hope someone can help me out to make this work. 希望有人可以帮助我完成这项工作。
Thanks so much. 非常感谢。
L 大号
This is the example of the datatable i have 这是我拥有的数据表的示例
Because you have already used a DataTable extension with CopyToDataTable
: 因为您已经在CopyToDataTable
使用了DataTable扩展名:
Dim rows = From row In dTable.AsEnumerable()
From item In CheckBoxList1.Items.Cast(Of ListItem)()
Where item.Selected = True AndAlso _
row.Field(Of String)("Song_Artist") = item.Text
Select row
If rows.Any() Then
Dim tblFiltered = tbl.CopyToDataTable()
End If
Or in method syntax (in VB.NET not very readable) 或方法语法(在VB.NET中不太可读)
Dim selected = CheckBoxList1.Items.Cast(Of ListItem).
Where(Function(i) i.Selected = True).
Select(Function(i) i.Text)
If selected.Any() Then
Dim rows = dTable.AsEnumerable().
Where(Function(r) selected.Contains(r.Field(Of String)("Song_Artist")))
If rows.Any() Then
Dim tblFiltered = rows.CopyToDataTable()
End If
End If
Finally, the NET 2.0 DataTable.Select approach: 最后,NET 2.0 DataTable.Select方法:
Dim selected As New List(Of String)
For Each item As ListItem In CheckBoxList1.Items
If item.Selected Then
selected.Add(String.Format("'{0}'", item.Text))
End If
Next
If selected.Count <> 0 Then
Dim rows = dTable.Select(String.Format(
"Song_Artist IN ({0})",
String.Join(",", selected)))
If rows.Length <> 0 Then
Dim tblFiltered = rows.CopyToDataTable()
End If
End If
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.