Click here to Skip to main content
15,917,062 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello.

I have DataTable object with columns
bool, Bitmap, string, string, string, string.

I want to use Linq so that I could make some kind of filtering on the first column (bool).

Here is what I use:

C#
var qqq = row in DataTable.AsEnumerable()
          where row.Field<bool>(ColumnNames[1]).ToString() == false.ToString()
          select row;

foreach (DataRow dataRow in qqq.ToList())
{
    dataRow.Delete();
}


Then I get the exception that I can't cast the field, why is that?
Posted
Comments
ZurdoDev 11-Nov-14 9:53am    
You said you wanted first column but then referenced ColumnNames[1] which would really be the second column. Perhaps all you need is to change to ColumnNames[0].
Zhivko Kabaivanov 11-Nov-14 9:59am    
No, ColumnNames is array that have the names of the columns in the DataTable.
The zero index ColumnName[0] is not initialized and the others goes like this ColumnName[1] = boolean,
ColumnName[2] = Read (Bitmap).
ZurdoDev 11-Nov-14 10:02am    
I'd debug it and make sure ColumnNames[1] is what you actually think it is.

C# arrays are zero-based, and you tell that the first column is a bool, so you should use ColumnNames[0] instead of ColumnNames[1]:
C#
where row.Field<bool>(ColumnNames[0]).ToString() == false.ToString()
 
Share this answer
 
It sounds like your bool column is nullable, and contains a null value. Try using .Field<bool?>(...) instead.

Also, there's no need to convert a bool or bool? to a string to compare it with another value of the same type.
C#
var qqq = row in DataTable.AsEnumerable()
          where row.Field<bool?>(ColumnNames[1]) == false
          select row;


Nullable Types (C# Programming Guide)[^]
 
Share this answer
 
Comments
Zhivko Kabaivanov 11-Nov-14 11:50am    
Nope, actually the solution was that when I init the data table: DataTable.Columns.Add(ColumnNames[1]);
there is no type specified and maybe the default type is String.
So when I compare the values in the Linq I get the expception.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900