Reputation: 7823
hope you are doing fine.
I have a datatable loaded from a database. I bind the datatable to a gridview on page_load. 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
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
Upvotes: 1
Views: 3838
Reputation: 460228
Because you have already used a DataTable extension with CopyToDataTable
:
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)
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:
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
Upvotes: 1