Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I correctly cast an item in a DataSet when it can potentially be null?

I have a dataset being returned by a stored proc and one of the items in it can potentially be null. I'm trying to convert each row in the dataset to a strongly typed object but I can't seem to cast the null value properly.

I've created a mock up of my scenario as follows:

DataSet ds = new DataSet();
ds.Tables.Add(new DataTable());
ds.Tables[0].Columns.Add("Name", typeof(string));
ds.Tables[0].Columns.Add("Amount", typeof(decimal));
ds.Tables[0].Rows.Add("My Name Here", null); //create row with a null item

DataRow dataRow = ds.Tables[0].Rows[0];

Person p = new Person
{ 
    Name = (string)dataRow["Name"], 
    Amount = (decimal)dataRow["Amount"]
}

Unfortunately I'm getting the following exception: System.InvalidCastException: Specified cast is not valid.

If I try to use a nullable type (decimal?) I get this error: System.NotSupportedException: DataSet does not support System.Nullable<>.

In the debugger I've done the following tests on the value in dataRow["Amount"]:

dataRow["Amount"] is decimal (false)
dataRow["Amount"] is decimal? (false)
dataRow["Amount"] == null (false)
dataRow["Amount"] is object (true)

All I can establish is that it's some sort of object...which isn't particularly helpful.

Can any of you spot what I'm doing wrong?

like image 426
mezoid Avatar asked Mar 01 '23 22:03

mezoid


1 Answers

You can use dataRow.IsNull("Amount") or Convert.IsDBNull(dataRow["Amount"]) or (dataRow["Amount"] as Decimal) != null.

like image 117
hvintus Avatar answered Mar 22 '23 23:03

hvintus