PDA

Click to See Complete Forum and Search --> : Assigning value to a Variable from SqlDataReader


Polariss
Nov 19th, 2006, 10:33 AM
How do I assign a value to a variable from the SqlDataReader.Read() method?? In Visual Basic it was done like this:


while sReader.Read()
Dim s As String = sReader("fieldnamefromdatabase")
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.


string s;
while (sReader.Read == true)
{
s = sReader["fieldnamefromdatabase"];
}


Any help is appreciated!!

Harsh Gupta
Nov 19th, 2006, 12:37 PM
1) You forgot to add brackets () after Read method:
while (sReader.Read() == 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!! ;)
'In this case, convert to string
s = Convert.ToString(sReader["fieldnamefromdatabase"]);

Otherwise, it is okay. Or are you getting some other error??

Polariss
Nov 19th, 2006, 12:53 PM
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.

Fishcake
Nov 19th, 2006, 02:55 PM
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 likes = sReader["fieldnamefromdatabase"].ToString();
or
s = sReader.GetString(sReader.GetOrdinal("fieldnamefromdatabase"));

There are also quite a few more ways of converting to a string.

Polariss
Nov 19th, 2006, 02:58 PM
Thanks for the help guys. Good advice. Was beating my head up for two days now.