473,396 Members | 1,968 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

access SqlDataReader using foreach

Hi everyone,

is there a way to access every record from a SqlDataReader via
"foreach" ?
I want to write a class which (besides doing some other stuff)
retrieves a recordset using SqlCommand.ExecuteReader().

Something like:

MyDbClass db = new MyDbClass("SELECT * FROM tblUsers");
foreach(MyRecordClass record in db.getRecordSet())
{
Console.WriteLine(MyRecordClass["UserId"]);
}

I know this has something to do with GetEnumerator (which SqlDataReader
implements) but I don't know how to start or if it's possible at all.

I hope someone can help me out.

Thanks in advance,

Kevin

Oct 17 '06 #1
2 16405
The syntax is:

IDataReader dataReader = // something to get an IDataReader
try
{
while (dataReader.Read())
{
if (!(dataReader.IsDBNull(0)))
{
Console.WriteLine(dataReader.GetString(0));
}
}
{
finally
{
if (!((dataReader == null)))
{
try
{
dataReader.Close();
}
catch
{
}
}
}

See full example at:


http://sholliday.spaces.live.com/blog/
5/24/2006 Entry
Custom Objects/Collections and Tiered Development

The CustomerController.cs file has it.

<ja*******@gmx.dewrote in message
news:11**********************@k70g2000cwa.googlegr oups.com...
Hi everyone,

is there a way to access every record from a SqlDataReader via
"foreach" ?
I want to write a class which (besides doing some other stuff)
retrieves a recordset using SqlCommand.ExecuteReader().

Something like:

MyDbClass db = new MyDbClass("SELECT * FROM tblUsers");
foreach(MyRecordClass record in db.getRecordSet())
{
Console.WriteLine(MyRecordClass["UserId"]);
}

I know this has something to do with GetEnumerator (which SqlDataReader
implements) but I don't know how to start or if it's possible at all.

I hope someone can help me out.

Thanks in advance,

Kevin

Oct 17 '06 #2
We use smth like List.ForEach:

public int ReadAll(SqlCommand cmd, Action<IDataRecordaction)
{
if (cmd == null)
throw new ArgumentNullException("cmd");

if (action == null)
throw new ArgumentNullException("action");

SqlDataReader reader = null;
try
{
OpenConnection(cmd);
reader = cmd.ExecuteReader();
while (reader.Read())
action(reader);
return reader.RecordsAffected;
}
finally
{
if (reader != null)
reader.Close();
CloseConnection();
}
}

and usage:
List<ProductTypeproducts = new List<ProductType>();

MainDB.ReadAll(cmd, delegate(IDataRecord record) {
ProductType pt =
(ProductType)Convert.ToInt32(record["ProductTypeId"]);
products.Add(pt);
});

also, you can replace delegate call with yield and use foreach then.

Oct 17 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: SBK | last post by:
I'm having a problem: I connect to an MS access db using jet oledb (it has a password). If the db doesn't have a password, everything works fine. If i do, access gets locked down (.ldb) with the...
1
by: Joris Kempen | last post by:
Hi people, I know that the question has come around sometimes: How to open an Access Report using ASP and export it to for example RTF. I'm trying to implement the first method of David...
1
by: caldera | last post by:
Hi, I want to find the web user control in the datalist. I iterate the datalist using foreach statement in the DataListItem and in thi DataListItem I iterate all Controls objects but I can't find...
1
khalidbaloch
by: khalidbaloch | last post by:
hi every one, how are you folf , hope fine dear Friends i want to get values of multi-dimensional arrays using foreach loop and after that print out the html using an other while loop , i tried...
3
by: Akira | last post by:
I noticed that using foreach is much slower than using for-loop, so I want to change our current code from foreach to for-loop. But I can't figure out how. Could someone help me please? Current...
0
by: nostradumbass77 | last post by:
Using Enterprise Library 2.0 (Jan 06) and .NET 2.0 (VB.Net 2005) Dim dbPF As Data.Common.DbProviderFactory Try dbPF = Data.Common.DbProviderFactories.GetFactory("System.Data.OleDb") db = New...
1
by: dzulai | last post by:
hello guys, im using VB6 to automate Access 2000 using opencurrentdatabase. basically, the VB part is just for login purposes and all other forms are in Access. i want to prevent the user from...
6
by: titan nyquist | last post by:
Can I step through a struct using foreach? I want a method that steps through a struct, and prints out the name/value of each member. Can it be done? The error I get when trying this is: ...
1
by: vit159 | last post by:
I have Data Recive it from stordProceder and i want to Get this data using foreach loop to equal it with local variable
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.