Queens Dev
Some more ASP.NET

Handle DB Null and Return Default in C#

May 9, 2008 at 2:21 AM by bjsetegn

 When retrieving data from a database you must handle null values.  The getDefaultIfDBNull method below will check if the value returned from the database is null.  If it is null then it will return the default value for that type of object.  For example if retrieving an int field from the database and passed a null value and TypeCode of Int32 it will return the default value of 0.  This helps streamline the checking for null proccess and ensures that all nulls are handled in a simliar way.

The Code:

        /// <summary>

        /// Checks if an object coming back from the database is dbnull.  If it is this returns the default

        /// value for that type of object.

        /// </summary>

        /// <param name="obj">Object to check for null.</param>

        /// <param name="typeCode">Type of object, used to determine what the default value is.</param>

        /// <returns>Either the object passed in or the default value.</returns>

        public static object getDefaultIfDBNull(object obj, TypeCode typeCode)

        {

            //If object is dbnull then return the default for that type.

            //Otherwise just return the orginal value.

            if (obj == DBNull.Value)

            {

                switch (typeCode)

                {

                    case TypeCode.Int32:

                        obj = 0;

                        break;

 

                    case TypeCode.Double:

                        obj = 0;

                        break;

 

                    case TypeCode.String:

                        obj = "";

                        break;

 

                    case TypeCode.Boolean:

                        obj = false;

                        break;

 

                    case TypeCode.DateTime:

                        obj = new DateTime();

                        break;

 

                    default:

                        break;

                }

            }

 

            return obj;

        }

 

This is a sample of a method that calls a stored procedure and needs to check for null.

 

        private void FillDetailInfo(int intDetailsId)

        {

            string conString = "";

            SqlDataReader dr;

 

            try

            {

                conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

                SqlConnection con = new SqlConnection(conString);

 

                SqlCommand cmd = new SqlCommand("uspGetDetails", con);

                cmd.CommandType = CommandType.StoredProcedure;

                cmd.CommandTimeout = 100000;

                cmd.Parameters.AddWithValue("@intDetailsId", intDetailsId);

 

                con.Open();

                dr = cmd.ExecuteReader();

 

                //Get details

                if (dr.Read())

                {

                    _id = (int)dr["Id"];

                    _desc = (string)SecurityTools.getDefaultIfDBNull(dr["desc"], TypeCode.String);

                    _isActive = (bool)SecurityTools.getDefaultIfDBNull(dr["ACTIVE"], TypeCode.Boolean);

                }

 

                con.Close();

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

End Code 

Comments

June 10. 2009 01:18

Franchises for sale

It's interesting, the blog engine platform seems very variable in form.  My design skills are not so good as my C coding though, I would be interested in seeing what additional skins you can get for it.  Nice blog btw, best wishes for it and keep up the posts. Smile  Kind regards,  Peter sims.

Franchises for sale

July 9. 2009 22:03

duck farmer

Brandon,

We like your website! please continue to provide Queens community with such a wonderful service.

duck farmers!

duck farmer

February 21. 2010 08:26

yoga ball chair

This reminds me of this quote: "Fortunately analysis is not the only way to resolve inner conflicts. Life itself still remains a very effective therapist." Karen Horney

yoga ball chair

February 21. 2010 08:42

Moriah Hernadez

Definitely agree with what you stated. Your explanation was certainly the easiest to understand. I tell you, I usually get irked when folks discuss issues that they plainly do not know about. You managed to hit the nail right on the head and explained out everything without complication. Maybe, people can take a signal. Will likely be back to get more. Thanks

Moriah Hernadez

February 22. 2010 06:33

Best Calling Card

Wonderful blog, i want to read your blog posts when I can. Is there a way to have these sent to my email and then i can read it when i can? let me know please.

Best Calling Card

February 26. 2010 01:31

payday loans

Do not go where the path may lead, go instead where there is no path and leave a trail.

payday loans

February 26. 2010 23:33

reverse phone lookup

Hey everybody. Interesting idea for a blog. I was just surfing the Internet for fun when I found your website. Terrific post. Thanks a ton for sharing your experience! It is great to see that some people still put in an effort into handling their websites. I'll be sure to check back from time to time.

reverse phone lookup

February 27. 2010 19:42

Origins skin care

Hi
I found your site through search at google.  Your article very useful for me, maybe for other people too.  Big Thanks

Regards
Orie

Origins skin care

March 1. 2010 19:29

marriage records

Interesting post, this is one of my favourite subjects and close to my heart. LOL. I love keeping up to date on all things new so i’ll definitely be bookmarking this website. Keep up the good work!

marriage records

March 2. 2010 02:51

Jennifer

Just found this with a bing search. Thought I would chime in and compliment you on your website.

Jennifer

March 2. 2010 16:35

Dee Putty

I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favorites blog page list and will be checking back soon. Please check out my site as well and let me know what you think.

Dee Putty

March 3. 2010 03:38

Refurbished Computers

Thank you for another fantastic blog. Where else could I get this kind of information written in such an incite full way? I have a project that I am just now working on, and I have been looking for such information... Regards…  

Refurbished Computers

March 4. 2010 19:17

Stretch mark removal

Thanks for this – I really enjoyed the article and a good deal of the information here I can certainly make use of.

Regards,
Dicky

Stretch mark removal

March 5. 2010 13:51

Mitchell Venner

I've encountered testers get into a zone where they continue logging follow-on bugs into the bug tracking system. This is passing if there are no different important tests left. Yet, I’ll bet there are. Bugs that will indirectly get fixed by previous bugs more often than not just make administrative work, which deducts from our uncommitted time to code and test.

Mitchell Venner

March 7. 2010 06:08

watch the pacific

Hello there.Sorry if my english language isn't good.however i just want to tell  i like this article a lot. thanx

watch the pacific

March 7. 2010 09:08

Neil Pechaira

I am very delighted to find this website.I wanted to thank you with regard to this great read!! I certainly appreciated every little bit of it and I've you bookmarked to look at new things you publish.

Neil Pechaira

March 8. 2010 13:54

moon in my room

Thanks for taking this opportunity to talk about this, I feel strongly about it and I benefit from learning about this subject. If possible, as you gain data, please update this blog with new information. I have found it extremely useful.

moon in my room

March 9. 2010 05:18

leather messenger bag

You made numerous nice ideas there. I done a search on the issue and learnt nearly all peoples will agree with your blog.

leather messenger bag

March 9. 2010 07:14

WoW Mobile

Do you know which cell phone services allow tethering?

WoW Mobile

March 9. 2010 11:24

NANCY FARRELL

Hey very nice blog!! Man .. Beautiful .. Amazing .. I will bookmark your blog and take the feeds also

NANCY FARRELL

March 9. 2010 17:47

computer running slow

Thanks for that, very interesting on the subject of Queens Dev | Handle DB Null and Return Default in C#. I will do some more searches for Queens Dev | Handle DB Null and Return Default in C#

computer running slow

March 10. 2010 02:31

kartenlegen per e-mail

great Info. Tweeted about it. I'll bookmark this post too later Smile.

kartenlegen per e-mail

March 10. 2010 04:29

WoW Mobile

Do you know which cell phone services allow tethering?

WoW Mobile

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading