Results 1 to 5 of 5

Thread: Assigning value to a Variable from SqlDataReader

  1. #1

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Posts
    104

    Assigning value to a Variable from SqlDataReader

    How do I assign a value to a variable from the SqlDataReader.Read() method?? In Visual Basic it was done like this:

    VB Code:
    1. while sReader.Read()
    2.      Dim s As String = sReader("fieldnamefromdatabase")
    3. end while

    I have tried converting this statement from VB to C# with no luck. Does anyone know how to perform this action.

    I have tried a couple of other things as well but here is the one I tried first.

    VB Code:
    1. string s;
    2. while (sReader.Read == true)
    3. {
    4. s = sReader["fieldnamefromdatabase"];
    5. }

    Any help is appreciated!!
    Last edited by Polariss; Nov 19th, 2006 at 12:44 PM.

  2. #2
    Smitten by reality Harsh Gupta's Avatar
    Join Date
    Feb 2005
    Posts
    2,938

    Re: Assigning value to a Variable from SqlDataReader

    1) You forgot to add brackets () after Read method:
    VB Code:
    1. while (sReader.Read[b]()[/b] == true)
    C# doesn't do it for you automatically as VB does!!

    2) Always Convert the value that you retrieve from DataBase to specific type or object. It's a good practice as it avoids unnecessary headaches!!
    VB Code:
    1. 'In this case, convert to string
    2. s = Convert.ToString(sReader["fieldnamefromdatabase"]);

    Otherwise, it is okay. Or are you getting some other error??
    Show Appreciation. Rate Posts.

  3. #3

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Posts
    104

    Re: Assigning value to a Variable from SqlDataReader

    I have put the brackets on the end of the Read() method I just forgot them that time. The error I was getting is a weird possible null statement error.

  4. #4
    Frenzied Member Fishcake's Avatar
    Join Date
    Feb 2001
    Location
    Derby, UK
    Posts
    1,092

    Re: Assigning value to a Variable from SqlDataReader

    It is because C# cannot implicitly convert from type object (returned by the datareader) and a string so you need to specify that it's a string.

    Either like
    Code:
    s = sReader["fieldnamefromdatabase"].ToString();
    or
    Code:
    s = sReader.GetString(sReader.GetOrdinal("fieldnamefromdatabase"));
    There are also quite a few more ways of converting to a string.

  5. #5

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Posts
    104

    Resolved Re: Assigning value to a Variable from SqlDataReader **RESOLVED**

    Thanks for the help guys. Good advice. Was beating my head up for two days now.

Posting Permissions

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



Click Here to Expand Forum to Full Width