0

I am retrieving propertyInfos from a given type.

When a property is of type Nullable<int> then I can not add the property type to the dataTable.columns collection because I get an exception:

System.NotSupportedException: ''DataSet' supports not System.Nullable<>.'

foreach (var prop in propertyInfos)
{
    if (prop.PropertyType == typeof(int?))
    {
        dataTable.Columns.Add(prop.Name, prop.PropertyType);
    }
    else
    {
        dataTable.Columns.Add(prop.Name, prop.PropertyType);

    }
}

What should I change in the if-clause to make it work?

I already added null or DBNull to the collection but that did not help?!

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Elisabeth
  • 20,496
  • 52
  • 200
  • 321
  • Did you just try int? int is also a type. You can debug and look which types you are getting while iterating your properties. So you can recognize to which type you have to compare against. When your property is from Nullable you can check for typeof(int?) and then get the underlying type via `Type yourIntType = Nullable.GetUnderlyingType(prop.PropertyType);` – Teneko Oct 18 '17 at 13:49
  • [Convert generic List/Enumerable to DataTable?](https://stackoverflow.com/a/5805044/3110834) – Reza Aghaei Oct 18 '17 at 14:05

1 Answers1

4

Use null coalescing operator and Nullable.GetUnderlyingType method for this purpose:

dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(
                              prop.PropertyType) ?? prop.PropertyType);
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • Not quite there, you also need to set the column to be nullable. – DavidG Oct 18 '17 at 13:52
  • No, I mean `var column = dataTable.Columns.Add(...); column.AllowDBNull = true;`(or `false` of course) – DavidG Oct 18 '17 at 13:55
  • 1
    @DavidG The default it true for [`AllowDBNull`](https://msdn.microsoft.com/en-us/library/system.data.datacolumn.allowdbnull(v=vs.110).aspx). – Reza Aghaei Oct 18 '17 at 14:07