Utility function to convert Type to SqlDbType

Ever needed to convert a System.Type to its corresponding System.Data.SqlDbTye? Here is a nice little utility function that helps you convert a System.Type to it’s corresponding System.Data.SqlDbType.

  1: private SqlDbType GetDBType(System.Type theType)
  2: {
  3:    SqlParameter param;
  4:    System.ComponentModel.TypeConverter tc;
  5:    param = new SqlParameter();
  6:    tc = System.ComponentModel.TypeDescriptor.GetConverter(param.DbType);
  7:    if (tc.CanConvertFrom(theType))
  8:    {
  9:        param.DbType = (DbType)tc.ConvertFrom(theType.Name);
 10:    }
 11:    else
 12:    {
 13:        // try to forcefully convert
 14:        try
 15:        {
 16:            param.DbType = (DbType)tc.ConvertFrom(theType.Name);
 17:        }
 18:        catch(Exception e)
 19:        {
 20:            // ignore the exception
 21:        }
 22:    }
 23:    return param.SqlDbType;
 24: }
Technorati Tags: ,,,
Related Posts with Thumbnails


Subscribe to our free RSS feed to keep up with what's happening at DemoGeek.com

At DemoGeek.com we try to explain the tech stuffs in as much detail as we can to help the not-so-tech-savvy of our friends understand and follow the tech stuffs.

Share/Save/Bookmark

Subscribe to DemoGeek.com
Avoid ThreadAbortException in ASP.NET with Response.Redirect Don’t start your user defined stored procs with SP_

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

4 comments so far

  1. Steve Miller
    #1

    Thank you for the code. This really saved my day.

  2. Alex Filipovici
    #2

    Hi,

    Just wanted to point out that this function should not be used with CLR, as the System.ComponentModel.TypeDescriptor is marked with the HostProtectionAttribute and it's use is disallowed by the SQL Server.

    Best regards.

  3. demogeek
    #3

    Thanks for the tip Alex. Appreciated!

  4. Johan
    #4

    Hi Alex.

    What would you suggest as alternative when you want to do this kind of conversion within a CLR?

    Regards.

    Johan

Leave a Reply





XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

About DemoGeek.com

DemoGeek.com brings you high quality articles, tutorials and how to's on everything related to Microsoft Windows, Mac OSX, iPhone, Useful Websites, Browsers, Software and Programming.

At DemoGeek.com you'll find step-by-step explanation of the technical issues explained in detail with screenshots and screencasts. Read More...

Contact |  FUG |  Disclaimer

Creative Commons License

Canonical URL by SEO No Duplicate WordPress Plugin