July 05, 2007

Convert System.Type to SqlDbType

Following function convert System.Type to SqlDbType. Note System.Stiring converts to SqlDbType.NVarChar

public static SqlDbType ToSqlDbType(Type type)
{
SqlParameter p1 = new SqlParameter();
System.ComponentModel.TypeConverter tc;
tc = System.ComponentModel.TypeDescriptor.GetConverter(p1.DbType);

if( tc.CanConvertFrom(type))
p1.DbType = (DbType)tc.ConvertFrom(type.Name);
else
{
try
{
p1.DbType = (DbType)tc.ConvertFrom(type.Name);
}
catch(Exception ex)
{
}
}

return p1.SqlDbType;
}