Askar

Utility function to convert Type to SqlDbType

In .NET on December 8, 2006 at 11:15 pm

Here is a nice utility function that helps you convert a System.Type to it’s corresponding System.Data.SqlDbType. Hope it’s useful.

private SqlDbType GetDBType(System.Type theType)
{
    SqlParameter param;
    System.ComponentModel.TypeConverter tc;
    param = new SqlParameter();
    tc = System.ComponentModel.TypeDescriptor.GetConverter(param.DbType);
    if (tc.CanConvertFrom(theType))
    {
        param.DbType = (DbType)tc.ConvertFrom(theType.Name);
    }
    else
    {
        // try to forcefully convert
        try
        {
            param.DbType = (DbType)tc.ConvertFrom(theType.Name);
        }
        catch(Exception e)
        {
            // ignore the exception
        }
    }
    return param.SqlDbType;
}
Advertisements
  1. This is just what I needed. Also, its the most compact solution I have seen. No large case or if statements.

    Thankyou very much

  2. Excelente! Esto es muy util. Gracias por este tip.

    -Hector Cervantes

  3. This is something I’d been looking to do for a long time. Thanks!

  4. great….
    looking for the same….

    Thanks

  5. can you go the other way with it?
    Get System.Type from SqlDbType

  6. WOW !!

    Thanks a lot dude

  7. thanks a lot!

  8. This is not working on compact framework,
    do you have any idea

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: