How to correctly filter a datatable (datatable.select)

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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;

Method 2

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

Method 3

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x