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:
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.
VB Code:
string s;
while (sReader.Read == true)
{
s = sReader["fieldnamefromdatabase"];
}
Any help is appreciated!!
Re: Assigning value to a Variable from SqlDataReader
1) You forgot to add brackets () after Read method:
VB Code:
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:
'In this case, convert to string
s = Convert.ToString(sReader["fieldnamefromdatabase"]);
Otherwise, it is okay. Or are you getting some other error??
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.
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.
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.