我有从数据库加载的数据表。我将数据表绑定到page_load上的gridview。现在我想通过用户选择过滤gridview,所以我制作了一个checkboxlist并在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()
使用上面的代码,如果复选框列表中只有一个选项,它可以过滤。我尝试自己循环复选框,但总是出错。希望有人可以帮助我完成这项工作。
非常感谢。
→
这是我拥有的数据表的例子
答案 0 :(得分:1)
因为您已经使用了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
或者在方法语法中(在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
最后,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