net beginner
net beginner

Reputation: 31

How do I convert a database object to int in C#?

How do I convert a database object to int in C#?

int uid = Convert.ToInt32(dt.Rows[0]["userid"].ToString());

Upvotes: 3

Views: 14570

Answers (3)

varadarajan
varadarajan

Reputation: 514

Use Null Check before Converting to integer.

DataRow row=dt.Rows[0];
int uid = row.IsNull("userid") ? 0 : (Convert.ToInt32(dt.Rows[0]["userid"]); 

Upvotes: 5

Brian Scott
Brian Scott

Reputation: 9361

You shouldn't convert the object to a string before converting to the int.

int uid = Convert.ToInt32(dt.Rows[0]["userid"]);

If you need to convert a string to an int then use;

int uid = int.Parse("1");

Upvotes: 6

Sarzniak
Sarzniak

Reputation: 297

Int32.Parse(...) ... - your ToString() method

Upvotes: 1

Related Questions