0

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

        }
    }
}
Zbigniew
  • 27,184
  • 6
  • 59
  • 66

1 Answers1

3

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)) {
aquinas
  • 23,318
  • 5
  • 58
  • 81
  • While this is a correct answer, I'm curious why OP wants to check whether Tables[0].Columns[3] is an int for each row, given the table definition won't change during the execution. Is that really what he wants to know, or is there a better solution for the problem at hand? – CodeCaster Feb 08 '13 at 17:33
  • Quite possibly the table contains disparate types of data and doesn't have a defined data type. – aquinas Feb 08 '13 at 17:37
  • Like an int for one row, a datetime for the other and a decimal for the next, all stored in a varchar column? Then that is the problem that needs to be solved, not the parsing. – CodeCaster Feb 08 '13 at 17:45
  • This works great aquinas, thank you. Of course, once this was in, switching on var was a great idea, thank you too Dan-o. I dont have any control over the database that generates this datatable and I want to insure that this piece of code wont grind to a hault if somehow a 'three' gets passed to me in this column. – rrankman Feb 08 '13 at 17:52