Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Looping Through a Data Adapter

Status
Not open for further replies.

kmfna

MIS
Sep 26, 2003
306
US
Hello all,

Does anyone know if there is a good way to loop through a data adapter after received from a database? I am planning to load up an array list of a class that I created. The only issue I've found is that I can't actually loop through the Dataset or the Data adapter, which has the data that I need to drop into the class and then add to the array list. In VB 6.0, I would have just used the .movenext property, I just haven't found anything like that in C#. It seems like all examples lead to binding the data adapter to a grid, which is not what I need it to do.

Thanks in advance, you're all great.

Kevin
 
I DataAdapter doesn't contain Data. DataSets, DataTables, and DataRows do. You need to loop through the .Rows() collection of your DataTable.

For example:

foreach(DataRow r in MyDataSet.Tables[0].Rows())
{
}
 
Awesome, thanks river, that was exactly what I needed.

Thanks,

Kevin
 
Kevin,
Just so that you know... you may also use the DataReader object which is client side forward-only resultset of data that has some similarities with the default ADO Recordset object. The DataReader does have a .MoveNext method, (although it's called Read, not MoveNext), and since it's a forward-only cursor, it's more efficient than the Dataset. If what you need is just read a few records from a data source, the DataReader is the object to use. The Dataset is more like a mini database which you don't really need if you're just reading records.

In any case, if you decide to use, this is how your code would look like:
Code:
SqlConnection cn = [blue]new[/blue] SqlConnection(...);

[blue]string[/blue] sqlText = "SELECT * FROM Publishers";
SqlCommand cmd = [blue]new[/blue] SqlCommand(sqlText, cn);

[green]// You obtain a DataReader object by using the
// Command object's ExecuteReader() method.[/green]
[b]SqlDataReader dr = cmd.ExecuteReader();[/b]

[green]// The Read method advances to the next record 
// and returns False when there are no more[/green]
[blue]while[/blue] (dr.Read())
{
   [green]//Do whatever you want with the data
   ...[/green]
}
JC


_________________________________________________
To get the best response to a question, read faq222-2244!
 
Thanks JC,

I have that part working, since I do need to be able to go back and forth between records (if rarely).

Thanks again,

Kevin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top