Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query a DataSet and iterate through the result?

Tags:

c#

.net

I have a DataSet which contains two tables, Publication and Owner, which are linked on Publication ID. How do I query the dataset? What I am trying to do is get all of the owners for a particular publication, and then I want to iterate over the resulting set, concatenate the owner names together and populate a label with the information...

But lets begin with, how do i query the dataset?

I also have a DataRelation, can I query that somehow to get the child rows for the current row?

Thanks.

like image 289
flavour404 Avatar asked Jul 16 '09 00:07

flavour404


People also ask

How do you iterate through ResultSet?

Iterating the ResultSet To iterate the ResultSet you use its next() method. The next() method returns true if the ResultSet has a next record, and moves the ResultSet to point to the next record. If there were no more records, next() returns false, and you can no longer.

Can we use for loop in SQL query?

In SQL Server, there is no FOR LOOP. However, you simulate the FOR LOOP using the WHILE LOOP.

How do I iterate through a cursor in SQL?

Normally, when we need data looping, we use either "Cursors" or "While loop" in SQL Server. Both are used with multiple rows to give decisions on a row-by-row basis. Cursors - Cursor is a database object used by applications to manipulate the data in a set on a row-by-row basis.


2 Answers

ADO.NET supports two fundamental approaches for performing filtering and sorting of datasets:

The DataTable Select Method - This method is overloaded to accept arguments to filter and sort data rows returning an array of DataRow objects.

The DataView object sort, filter and find methods - This object uses the same filter arguments supported by the Select method, but the DataView exposes structures that can be bound to data-aware controls. See DataView.RowFilter

Iterating over filtered rows is as easy as:

DataTable dt;
...
foreach (DataRow dr in dt.Select(filter))
{
    // ...
}

This article contains several examples: A Practical Guide to .NET DataTables, DataSets and DataGrids - Part 1

like image 200
Mitch Wheat Avatar answered Sep 23 '22 14:09

Mitch Wheat


You could look into LINQ to Dataset, which allows you to perform queries against DataSets with multiple tables. You can perform joins between the tables on the appropriate columns amongst other things.

like image 30
tbreffni Avatar answered Sep 24 '22 14:09

tbreffni