I have a DataRow loaded with data from an SQL view. I then read the columns of the DataRow and assign them to an Object which properties are actually the column names of the sql view. The goal is to have a generic function that returns the value of the column dynamically. However, if the passing value is numeric insteaad of AlphaNumeric, then it seems that the value is interpreted as Int32 and not as String. The exception is the following: Unable to cast object of type 'System.Int32' to type 'System.String'.
This is the calling function:
foreach (DataRow dr in dt)
{
MyObject myObject = new MyObject(dr);
//Continue with myObject
}
In the constructor of MyObject, I am trying to read the values of DataRow and set them to object's properties. I have tried the following
public MyObject(DataRow dr)
{
_comments = Utils.GetDbValue<string>(dr, "comments"); //fails if "comments" == "1"
_comments = Utils.GetDbString(dr, "comments"); //fails if "comments" == "1"
_comments = dr.Field<string>("comments"); //fails if "comments" == "1"
}
_comments is a private field of MyObject whereas "comments" is the column name. If "comments" is filled in correctly (like an actual string), then I have no problems whatsoever. If the value is an integer (for instance '1'), then it is interpreted as Int32 and throws a cast exception.
public static class Utils
{
public static T GetDbValue<T>(DataRow dataRow, string columnName)
{
int index = dataRow.Table.Columns.IndexOf(columnName);
if (index < 0 || index > dataRow.ItemArray.Count())
{
return default(T);
}
else
{
return (T)dataRow[index];
}
}
//Cannot be used for other data types (i.e Int, DateTime)
public static string GetDBString(DataRow dataRow, string columnName)
{
if (dataRow.IsNull(columnName))
{
return string.Empty;
}
else
{
return dataRow.Field<string>(columnName);
}
}
}
EDIT:
It seems that this function seems to be working neatly so far, although it is not tested but for Integer, String, DateTime and Decimal types.
public static T GetDbValue<T>(DataRow dataRow, string columnName)
{
int index = dataRow.Table.Columns.IndexOf(columnName);
if (dataRow.IsNull(columnName) || index < 0 || index > dataRow.ItemArray.Count())
{
return default(T);
}
else
{
return (T)dataRow[index];
}
}
Please check below its might usefull for you