473,779 Members | 1,913 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Exec uteReader().

Something like:

MyDbClass db = new MyDbClass("SELE CT * FROM tblUsers");
foreach(MyRecor dClass record in db.getRecordSet ())
{
Console.WriteLi ne(MyRecordClas s["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 16452
The syntax is:

IDataReader dataReader = // something to get an IDataReader
try
{
while (dataReader.Rea d())
{
if (!(dataReader.I sDBNull(0)))
{
Console.WriteLi ne(dataReader.G etString(0));
}
}
{
finally
{
if (!((dataReader == null)))
{
try
{
dataReader.Clos e();
}
catch
{
}
}
}

See full example at:


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

The CustomerControl ler.cs file has it.

<ja*******@gmx. dewrote in message
news:11******** **************@ k70g2000cwa.goo glegroups.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.Exec uteReader().

Something like:

MyDbClass db = new MyDbClass("SELE CT * FROM tblUsers");
foreach(MyRecor dClass record in db.getRecordSet ())
{
Console.WriteLi ne(MyRecordClas s["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(SqlComm and cmd, Action<IDataRec ordaction)
{
if (cmd == null)
throw new ArgumentNullExc eption("cmd");

if (action == null)
throw new ArgumentNullExc eption("action" );

SqlDataReader reader = null;
try
{
OpenConnection( cmd);
reader = cmd.ExecuteRead er();
while (reader.Read())
action(reader);
return reader.RecordsA ffected;
}
finally
{
if (reader != null)
reader.Close();
CloseConnection ();
}
}

and usage:
List<ProductTyp eproducts = new List<ProductTyp e>();

MainDB.ReadAll( cmd, delegate(IDataR ecord record) {
ProductType pt =
(ProductType)Co nvert.ToInt32(r ecord["ProductTyp eId"]);
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
2173
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 access db 'Admin' user. Closing the Windows Form that uses the oledbconnection has no effect on the ldb (even though i close the connection etc). I can't delete the ldb manually or programatically (after the .net appication is closed - the ldb...
1
2946
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 Cline: http://www.15seconds.com/issue/981216.htm
1
4585
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 web user control, but I found that it is in the namedcontrols. How can I find the web user control using foreach in the datalist Thanks.
1
4338
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 alot but did not successed accutly i want to create an yahoo api websearch application i got a sample from developer.yahoo.com for this purpose ,this sample uses unserialize/serialize php here is the code exapmle <?php // Parsing Yahoo! REST...
3
33371
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 code is here: foreach ( string propertyName in ht.Keys ) { this.setProperty( propertyName, ht );
0
3864
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 Microsoft.Practices.EnterpriseLibrary.Data.GenericDatabase( _ "Provider=Microsoft.Jet.OLEDB.4.0;Data
1
1717
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 opening multiple instances of Access, so i disabled the buttons (except for Quit button) in the login screen. the problem now is when i close Access, i cant figure a way to enable the buttons again. the GotFocus event of the login screen, where i coded...
6
13213
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: "foreach statement cannot operate on variables of type '...' because '...' does not contain a public definition for 'GetEnumerator'. And it points me to http://msdn2.microsoft.com/en-us/library/t51esaeb(vs.80).aspx I guess this is the answer, but...
1
1562
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
10306
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10138
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10074
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9930
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8961
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5373
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2869
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.