Reputation: 31
How do I convert a database object to int in C#?
int uid = Convert.ToInt32(dt.Rows[0]["userid"].ToString());
Upvotes: 3
Views: 14570
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
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