rrankman
rrankman

Reputation: 11

Why does IS check not work for datarow

I have a datarow that has an integer in one of the columns. However the following code does not evaluate as true. I'm having a hard time understanding why. What am I missing?

foreach (DataRow dr in dataset.Tables[0].Rows)
{
    //this evaluates as false, even when I have a valid castable INT value in the column (as an object).
    if (dr[3] is int)
    {
        if (Convert.ToInt32(dr[3]) == 3)
        {
            //do something with row

        }
        else if (Convert.ToInt32(dr[3]) == 4)
        {
            //do someting else with row

        }
    }
}

Upvotes: 0

Views: 76

Answers (1)

aquinas
aquinas

Reputation: 23796

As others have said, you probably have a string which can be converted to an int, but not casted to an int.

Try this:

int val;

if (Int32.TryParse(dr[3].ToString(), out val)) {

Upvotes: 3

Related Questions