Monday, February 5, 2007

System.Data.EvaluateException: Cannot perform '=' operation on System.Int16 and System.String

This exception was thrown while filtering out rows from a DataTable with an incorrect filter expression. See the sample code shown below...

DataTable dt = GetDataTable();        
DataRow[] drs = dt.Select("ID='" +param + "'");
private DataTable GetDataTable()
{
    DataTable dt = new DataTable();
    dt.Columns.Add(new DataColumn("ID", typeof(Int16)));
    DataRow dr;
    for (int i = 0; i <= 100; i++)
    {
        dr = dt.NewRow();
        dr["ID"] = i;
        dt.Rows.Add(dr);            
    }
    return dt;
}

The GetDataTable() method just returns a sample DataTable with one column of Type Int16. The param in the filter expression is of string type. The expression works fine as long as the param string is a number, like 0, 1, 2... since ID is an Int16 column. The expression can be framed either as "ID = '2'" or "ID = 2". When param is an empty string or null, the above exception is thrown as these types of strings cannot be converted into a type that is equivalent to the comparing column (Int16).

So the next time when you use a filter expression to filter out rows from a DataTable ensure that you use the right Data Types.

1 comment:

Anonymous said...

If you try to obtain system management info for "Win32_Fan" and "Win32_TemperatureProbe" no properties or property values are displayed. I want to access the CPU temperature sensor but cannot find a way to do it. I have browsed the net but have not found any method which works on my PC. Any suggestions?