Possible Duplicate:
Best way to check if a Data Table has a null value in it
I want to know what should be the way to check DBNull for a DataTable - DataRow values.
I have a DataRow which fetches information from database from rows type like :
varchar, money, Int and so on.
What should be my (simple and sweet) approach to handle such situation.
Often when working with DataTables you have to deal with this cases, where the row field can be either null or DBNull, normally I deal with that like this: The 'as' operator returns null for invalid cast's, like DBNull to string, and the '??' returns the term to the right of the expression if the first is null.
This blog explains the behavior of DBNull in C# and explains the methods to handle it. Let's talk about DBNull today. DBNull represents a nonexistent value returned from the database. In a database, for example, a column in a row of a table might not contain any data whatsoever.
In the case above, if row comes back as DBNull, then value will become null instead of throwing an exception.
Well, later I found that database/sql package does provide NullInt64, NullString, NullFloat64 etc., structs to handle null values. These structs are embedded with one additional field Valid which is boolean type, indicates whether field is NULL or not. Look at the one of struct ( NullInt64) implementation here.
Try:
foreach(DataRow row in table.Rows)
{
object value = row["ColumnName"];
if (value == DBNull.Value)
{
}
else
{
}
}
Try this
For varchar
string val = dr["name"].ToString();
For int
int? val = dr["status"] == DBNull.Value ? (int?) null : Convert.ToInt32(dr["status"]);
Do the same for Money, Decimal
as done for int
replacing with respective .Net
types
You can use an extension method like this;
public static T GetValue<T>(this OracleDataReader reader, string fieldName)
{
T result = default(T);
int index = reader.GetOrdinal(fieldName);
if (reader.IsDBNull(index))
{
return default(T);
}
if (typeof(T) == typeof(string))
{
result = (T)Convert.ChangeType(reader.GetString(index), typeof(T));
}
if (typeof(T) == typeof(int))
{
result = (T)Convert.ChangeType(reader.GetInt32(index), typeof(T));
}
if (typeof(T) == typeof(DateTime))
{
result = (T)Convert.ChangeType(reader.GetDateTime(index), typeof(T));
}
if (typeof(T) == typeof(byte[]))
{
OracleLob blob = reader.GetOracleLob(index);
result = (T)Convert.ChangeType(blob.Value, typeof(T));
}
return result;
}
And you can use like string title = reader.GetValue<string>("title")
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