How to filter a dataset in a For...Each loop?

Agent707

Member
Joined
Jul 9, 2004
Messages
15
Location
Knoxville, TN
I have a dataset with a column "KeyName". I need to filter my for each loop on this if I can.
Code:
For Each oDataRow In oDataSet.Tables(0).Rows
    code
Next
Something like this...
e.g.
Code:
For Each oDataRow In oDataSet.Tables(0).Rows (where "KeyName = SomeValue")
    code
Next
The reason I need to do this is THIS For Each loop is nested inside another one where I am looping though each "KeyName" in an XML Document.
Looks like this.
Code:
For Each lo_node In lo_nodeSet.SelectNodes("attachments")
    lo_attachments = GetDataElement(lo_node, "attachments")
    ls_name = lo_attachments.GetAttribute("KeyName")
    some code
    For Each oDataRow In oDataSet.Tables(0).Rows (where KeyName = ls_name)
        BUNCH of code
    Next 
    more code
Next
Hope that makes sense. Thanks
 
Could you not use a DataView to filter the DataTable to the values you need and then loop through those rows rather than doing the filtering yourself as part of the loop?
 
My post count reflects my experience with .Net. :D This is my first attempt at a .net app using a database, so my knowledge on these datasets...etc. is kind of limited.

But what you say sounds good. After messing with it a bit. I came up with this.
Code:
oDataView = oDataTable.DefaultView
For Each lo_node In lo_nodeSet.SelectNodes("attachments")
    lo_attachments = GetDataElement(lo_node, "attachments")
    ls_name = lo_attachments.GetAttribute("KeyName")
    oDataView.RowFileter = "name = " & ls_name & ""
    some code
    For Each oDataRow In oDataView.Table.Rows
        some code
    Next 
    more code
Next
And works great. Thanks!

These .net data objects are starting to click a little bit now.
 
This shouldnt work as expected.
You are ignoring the view with oDataView.Table.Rows.
You have to use
Code:
oDataView = oDataTable.DefaultView
For Each lo_node In lo_nodeSet.SelectNodes("attachments")
    lo_attachments = GetDataElement(lo_node, "attachments")
    ls_name = lo_attachments.GetAttribute("KeyName")
    oDataView.RowFileter = "name = " & ls_name & ""
    some code
    For Each oDataRowView In oDataView
        some code
    Next 
    more code
Next
 
I dont see why you say "This shouldnt work"...? :confused:

A Dataview object has a Table (DataTable) object, which has a Rows (DataRowCollection) object... Its a simple loop through the rows collection.

And it works perfectly.
 
The Table in DataView is the unfiltered Table.
So you are not looping through the filtered values.

Easier for your purpose would be the DataTable.Select() funktion.
 
Back
Top