I have code like this:
foreach (DataRow row in dataTable.Rows)
{
if ((string)row["Forename"] != record.Forename)
{
// Do something
}
}
Works great but if row["Forename"]
is null
in the database, it is actually DBNull
here and it can't cast DBNull
to a string, or perform the comparison between DBNull
and string
. Some values are also nullable<int>
, and it can't compare DBNull
with int?
Is there a helper method to let me do nice comparisons or do I have to write an extension method myself?
You can use the DataRow.Field
extension method which supports nullable types:
foreach (DataRow row in dataTable.Rows)
{
int? id = row.Field<int?>("ID");
if(id.HasValue)
{
Console.Write("ID: " + id.Value);
}
}
Since string
is a reference type it will be null
by default. You can use DataRow.IsNull
instead to check whether it is DBNull.Value
or not:
foreach (DataRow row in dataTable.Rows)
{
if(row.IsNull("Forename"))
{
// ...
}
else
{
string foreName = row.Field<string>("Forename");
Console.Write("ForeName: " + foreName);
}
}
You can write your own extension method like this
public static T GetField<T>(this DataRow row,string columnName)
{
object value = row[columnname];
return (value != DbNull.Value)? (T)value : default(T);
}
Then you can use
if (row.GetField<string>(columnname) != record.Forename)
{
// Do something
}
This extension should support nullable types also
var value = row.GetField<int?>(columnname);
The only difference with DataRowExtension.Field and our implementation is that it will throw exception when we're trying to cast DbNull.Value
to any value type(except nullable type) in such case this method will return default value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With