[Newbie] SqlDataReader - What is the best or proper way to gain access to the field value?

D

DaBrain

Many thanks in advance!

....

SqlDataReader reader = cmd.ExecuteReader();
....

Working with:

string mystring;
bool mybool;
int myint;


I see this many ways in examples, what is the best or proper way to
gain access to the field value?


String:
mystring = reader["stringval"].ToString();
mystring = (string)reader["stringval"];


Boolean:
mybool = Convert.ToBoolean(reader["boolfield"].ToString());
mybool = Convert.ToBoolean(reader["boolfield"]);
mybool = (bool)reader["boolfield"];

int:
myint = Convert.ToInt32(reader["intfield"].ToString());
myint = Convert.ToInt32(reader["intfield"]);
myint = (int)reader["intfield"];


Many thanks in advance!
 
A

Alexey Smirnov

Many thanks in advance!

...

SqlDataReader reader = cmd.ExecuteReader();
...

Working with:

string mystring;
bool mybool;
int myint;

I see this many ways in examples, what is the best or proper way to
gain access to the field value?

String:
mystring = reader["stringval"].ToString();
mystring = (string)reader["stringval"];

Boolean:
mybool = Convert.ToBoolean(reader["boolfield"].ToString());
mybool = Convert.ToBoolean(reader["boolfield"]);
mybool = (bool)reader["boolfield"];

int:
myint = Convert.ToInt32(reader["intfield"].ToString());
myint = Convert.ToInt32(reader["intfield"]);
myint = (int)reader["intfield"];

Many thanks in advance!


Convert.ToInt32 could parse from string.

For example, here's a string
myint = Convert.ToInt32(reader["intfield"].ToString());

here's an int
myint = (int)reader["intfield"];

It means use

myint = Convert.ToInt32(reader["intfield"].ToString());
myint = Convert.ToInt32(reader["intfield"]);

for string values

and

myint = (int)reader["intfield"];

for int

The same for others...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top