SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Member
    Join Date
    May 2008
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    SQLDataReader - Using a Foreach to iterate through columns?

    I'm trying to iterate through the columns for each row of a SqlDataReader so that I can retrieve the (column name, value) pair from a row in the reader.

    Right now I'm manually referencing the SQL column like such:

    PHP Code:
    while (reader.Read()) {
        
    Response.Write(reader["categoryName"]+" - " reader["categoryID"];

    But I'd like to reference all the values in the reader automatically. Is there a way to get the column name, value for each item in a row? Something like this would be great:

    PHP Code:
    while (reader.Read()) {
        foreach(
    string columnName in reader){
            
    Response.Write(reader[column]+ " - ");
        }

    Anyone know how to achieve this kind of functionality?

    I am a PHP programmer by trade and if I'm unclear in anyway I can clarify. Any help is greatly appreciated!

  2. #2
    SitePoint Zealot
    Join Date
    Mar 2005
    Posts
    162
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Check out the Item property or GetValue of SqlDataReader.

    One or both of those should work.
    Web Application Development & Maintenance

  3. #3
    SitePoint Wizard
    Join Date
    Feb 2007
    Posts
    1,274
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No, the method to use is GetName - given an ordinal it will return the name of the column in that position. The FieldCount property will return the number of fields.

  4. #4
    SitePoint Zealot
    Join Date
    Mar 2005
    Posts
    162
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by honeymonster View Post
    No, the method to use is GetName - given an ordinal it will return the name of the column in that position. The FieldCount property will return the number of fields.
    He wants to get the value for the field, right? All GetName does is return the name of the field(i didnt confirm this though).
    Web Application Development & Maintenance

  5. #5
    SitePoint Wizard
    Join Date
    Feb 2007
    Posts
    1,274
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by eron19 View Post
    He wants to get the value for the field, right? All GetName does is return the name of the field(i didnt confirm this though).
    Well, looking at it again it seems he wants both.

  6. #6
    SitePoint Zealot
    Join Date
    Mar 2005
    Posts
    162
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    so GetValue and GetName is what he should be using then. cool.
    Web Application Development & Maintenance


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •