Setting a DataRow item to null
You need to cast them both to objects like so:
row[i] = !string.IsNullOrWhiteSpace(data[i]) ? (object)data[i] : (object)DBNull.Value;
I'm working on Asp.Net MVC 5 C# Web Application and did like this and working fine
rw[6] = (qry.PODate != null) ? qry.PODate : (object)DBNull.Value;
The problem is because of the operation you are using. Since DBNull.Value
is not a string, you can't use the conditional operator. This is because, from the conditional operator docs:
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
Try doing this:
if (!string.IsNullOrWhiteSpace(data[i]))
row[i] = data[i];
else
row[i] = DBNull.Value;
This bypasses the conversion requirements for both sides to be the same. Alternatively, you can cast both to a System.Object
explicitly, and still use the conditional operator.