Once you have data loaded into a DataRow or SqlDataReader, you’d typically do something like this:
string someValue = (string)drData["MyValue"];
In order to place it in the variable, you need to cast the type correctly (in this example, using the(string)). Also, what happens if “MyValue” is null? You’ll need to do an additional check, and then assign the value you want for the situations where it is null.
Today’s tip uses generics to return the correct type. It also allows you to return a default value if the value is null.
/// <summary>
/// Gets the data row value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="valueName">Name of the value.</param>
/// <param name="drData">The dr data.</param>
/// <param name="defaultValue">The default value. Note, this must be cast to the expected return type. For example, decimal.Parse("0").</param>
/// <returns></returns>
protected T GetDataRowValue<T>(string valueName, DataRow drData, T defaultValue)
{
if (drData[valueName] == DBNull.Value)
return defaultValue;
else
return (T)drData[valueName];
}
protected T GetDataRowValue<T>(string valueName, SqlDataReader drData, T defaultValue)
int myID = GetDataRowValue("SomeID", drData, 0);
DateTime myDate = GetDataRowValue("SomeDate", drData, DateTime.Now);
decimal myAmt = GetDataRowValue("SomeDecimalAmount", drData, decimal.Parse("0"));
string myString = GetDataRowValue("SomeString", drData, String.Empty);
Powered by: newtelligence dasBlog 2.3.9074.18820
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2012, © Copyright 2010
E-mail