ADO.NET provides two different ways to filter data: either using a
DataView and a RowFilter, or using a DataTable.Select().
Here are some examples of a DataView/RowFilter - you can essentially define a custom "view" of a datatable, based on a filter criteria, and then iterate through the items in
the view:
string cFilter; // Examples of RowFilter
cFilter = " Amount > 1000 ";
cFilter = "FirstName = 'Ken' OR EmpFlag = true";
cFilter = " City LIKE '%whatever%' ";
cFilter = "EmployeeID IN (12,144,54)";
// This one assumes a Parent Relation....it's to demonstrate that if you have an ADO.NET relation,
// you can specify Parent/Child syntax
cFilter = "Parent(RelName) = 'National'";
string cSort = "Location ASC, Salary DESC";
DataView Dv = new DataView(MyTable, cFilter, cSort, DataViewRowState.CurrentRows);
// you can now iterate through the items in the Dv Collection
foreach(DataRowView drv in Dv)
...
You can also use a DataTable.Select(). The results of a DataTable.Select()
are a collection of DataRow objects. You can use the same filter and sort syntax
as you used for a DataView:
DataRow[] aRows = MyTable.Select(cFilter,cSort);
foreach(DataRow oRow in aRows)
// process the oRow object, using the column objects for the row
Typically you'll want to use the dataview/rowfilter when you want to bind the results to
a control that's capable of reading a dataview. Use DataTable.Select() when you
want to manually loop through the resulting rows.
If you have a table with a primary key, you can do an ADO.NET FIND (similar to a SEEK)
MyDataTable.PrimaryKey = new DataColumn[] {MyDataTable.Columns["MyPrimaryKey"]};
DataRow dr = MyDataTable.Find(111);
Here are two of Kevin's articles in CoDe magazine that cover some of these
ADO.NET topics.
http://www.code-magazine.com/Article.aspx?quickid=0601031
http://www.code-magazine.com/Article.aspx?quickid=0607061
from a solution provided by Kevin Goff in Message #1142200
|