How to correctly filter a datatable (datatable.select)
Asked Answered
L

3

10
Dim dt As New DataTable
Dim da As New SqlDataAdapter(s, c)

        c.Open()
        If Not IsNothing(da) Then
            da.Fill(dt)
            dt.Select("GroupingID = 0")
        End If

        GridView1.DataSource = dt
        GridView1.DataBind()
        c.Close()

When I call da.fill I am inserting all records from my query. I was then hoping to filter them to display only those where the GroupingID is equal to 0. When I run the above code. I am presented with all the data, the filter did not work. Please can you tell me how to get this working correctly. Thanks.

Labana answered 17/6, 2010 at 8:54 Comment(0)
T
25

dt.Select() returns an array of DataRows.

Why don't you use a DataView?

 DataView dv = new DataView(dt);
 dv.RowFilter = "GroupingID = 0";
 GridView1.DataSource = dv;
Twandatwang answered 17/6, 2010 at 8:59 Comment(1)
Very simple and effective answer. Thank you.Eastertide
D
3

Junt in case... Think you've got a small typo in your VB.NET code. It should be dv.RowFilter instead of dv.RowStateFilter, so:

Dim dt As New DataTable
Dim dv As New DataView(dt)
dv.RowFilter = "GroupingID = 0"
DataGridView1.DataSource = dv
Demonolater answered 31/7, 2020 at 20:39 Comment(2)
Hi Sergio, welcome to SO this wont help us out much because your answer is identical as accepted answer. please take a tour here stackoverflow.com/tourSnoopy
My comment was meant to show on the post below that shows code in VB.NET that effectively has a typo.Friedlander
S
1

The accepted answer is correct, though it should have been given in vb.net to better benefit the one that asked the question. Here it is in VB.Net:

Dim dt As New DataTable:Dim dv As New DataView(dt):dv.RowStateFilter = "GroupingID = 0":DataGridView1.DataSource = dv
Stillas answered 26/7, 2020 at 9:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.