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

13,987

Solution 1

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");

Solution 2

Use Null Check before Converting to integer.

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

Solution 3

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

Share:
13,987
net beginner
Author by

net beginner

Updated on June 27, 2022

Comments

  • net beginner
    net beginner almost 2 years

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

    int uid = Convert.ToInt32(dt.Rows[0]["userid"].ToString());
    
    • R. Martinho Fernandes
      R. Martinho Fernandes about 13 years
      What is the type of the database column? What happens with that code? (Also, if you want to convert it to int, why are you converting it to a string?)
  • R. Martinho Fernandes
    R. Martinho Fernandes about 13 years
    1. C# is case-sensitive. 2. Put four spaces before code to format it as code. Use > for quote blocks. More info at the Markdown editing help page.
  • Brian Scott
    Brian Scott about 13 years
    @martinho, cheers, I'm not in front of an IDE at the moment to test the code.