none
Check type of Column in DataRow RRS feed

  • Question

  • Hi all,

     

    I have the following code and I want to check if a column of a row expects a boolean or not.  However, the condition is never triggered although I declared some columns as boolean in the DataTable.

     

     

    Code Snippet

    DataRow dr;

     

    dr = DataStorage.Instance.CareMoments.NewRow();

     

    for (int y = 0; y < FieldList.Length - 1; y++)

    {

    if (dr[y].GetType() == typeof(bool))

    {

    //do something

    }

    }

     

    Is this the wrong way to check it?  What is the correct way?

     

    Thanks in advance.

    Saturday, January 26, 2008 1:12 AM

Answers

  • That's not working, in all likelihood, because the column has AllowDBNulls set to True, and you're testing an empty row that you just created with NewRow().  The columns in the your new row all contain an object of type System.DBNull, not of type System.Boolean or whatever.

     

    The right way to check the data type of the column is to check the DataColumn - that's the schema for the column - rather than the value of that column in the current DataRow.  Thus:

     

    Code Snippet

    foreach (DataColumn c in dr.Table.Columns)

    {

       if (c.DataType == typeof(System.Boolean))

       {

          // do something - though if what you're planning to do is set dr[c] to

          // true or false, you might want to establish default values for the

          // columns instead.

       }

    }

     

     

     

    Saturday, January 26, 2008 4:07 AM

All replies

  • That's not working, in all likelihood, because the column has AllowDBNulls set to True, and you're testing an empty row that you just created with NewRow().  The columns in the your new row all contain an object of type System.DBNull, not of type System.Boolean or whatever.

     

    The right way to check the data type of the column is to check the DataColumn - that's the schema for the column - rather than the value of that column in the current DataRow.  Thus:

     

    Code Snippet

    foreach (DataColumn c in dr.Table.Columns)

    {

       if (c.DataType == typeof(System.Boolean))

       {

          // do something - though if what you're planning to do is set dr[c] to

          // true or false, you might want to establish default values for the

          // columns instead.

       }

    }

     

     

     

    Saturday, January 26, 2008 4:07 AM
  • Thanks for the explanation, with the check on DataColumn it works perfectly.

     

    Monday, January 28, 2008 1:58 AM