tags:

views:

75

answers:

1

I have a DataTable that contains columns that would contain DbNull values. I want to use Linq and output a new DataTable but I want the DbNull values to be perserved. Here is an example:

        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("C1",System.Type.GetType("System.String")));
        dt.Columns.Add(new DataColumn("C2",System.Type.GetType("System.String")));
        DataRow row;
        row = dt.NewRow();
        row["C1"] = "Hello";
        row["C2"] = "World";
        dt.Rows.Add(row);
        row = dt.NewRow();
        row["C1"] = DBNull.Value;
        row["C2"] = "World";
        dt.Rows.Add(row);

        var cars1 = from car in dt.AsEnumerable()
                    where car.Field<String>("C2") == "World"
                    select car;
        DataTable cars2 = cars1.CopyToDataTable();

How can the C1 column of the second row have the DbNull value be perserved in cars2 DataTable?

+1  A: 

Thomas is correct - CopyToDataTable() does nothing special to DBNull field values. However, the Field<T> extension method on DataRow does return null for DBNull - were you using that to test cars2?

dahlbyk