In the code below I get colType
which is a code number for the type. But how would I convert that number into the actual type? Thx!!
for (int j = 0; j < dvColumns.Count; j++)
{
// Get the name of the column.
drvCols = dvColumns[j];
colName = drvCols.Row.ItemArray[3].ToString();
// Get columns data type code and save it off.
colType = Convert.ToInt32(drvCols.Row.ItemArray[11]);
}
It's even simpler:
Type type = Type.GetType("System." + colType);
If you want to convert a value to that type you can use the typecode directly
Convert.ChangeType(value, colType);
Using a switch statement:
public static Type ToType(this TypeCode code)
{
switch (code)
{
case TypeCode.Boolean:
return typeof(bool);
case TypeCode.Byte:
return typeof(byte);
case TypeCode.Char:
return typeof(char);
case TypeCode.DateTime:
return typeof(DateTime);
case TypeCode.DBNull:
return typeof(DBNull);
case TypeCode.Decimal:
return typeof(decimal);
case TypeCode.Double:
return typeof(double);
case TypeCode.Empty:
return null;
case TypeCode.Int16:
return typeof(short);
case TypeCode.Int32:
return typeof(int);
case TypeCode.Int64:
return typeof(long);
case TypeCode.Object:
return typeof(object);
case TypeCode.SByte:
return typeof(sbyte);
case TypeCode.Single:
return typeof(Single);
case TypeCode.String:
return typeof(string);
case TypeCode.UInt16:
return typeof(UInt16);
case TypeCode.UInt32:
return typeof(UInt32);
case TypeCode.UInt64:
return typeof(UInt64);
}
return null;
}
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