Home > asp.net features, Best Practices of ASP.Net > Handling DBNull.Value

Handling DBNull.Value

Every asp.net developer use DbNull.Value when writing code to communicate with database. But it could sometimes be quite painful when you want to write with a null-coalescing or ?: operator. The same would be when getting something from database and type checking.

For example in this code snippet I wrote a function which stores a comment in database. As userWebsite is an optional parameter so it could be null and if database expects null then you need to send DBNull.Value. To make it adjustable in ?: operator you just have to cast into an object. like;
Value = userWebsite != null ? userWebsite : (object)DBNull.Value.
I tested this code in fw 4.0 only, so I’m not sure about older versions.

internal int SaveComment(string name, string email, string comment, string? userWebsite)
        {
            SqlCommand _command = new SqlCommand
            {
                Connection = new SqlConnection { ConnectionString = "connection string" },
                CommandType = CommandType.StoredProcedure,
                CommandText = "csp_comment_save",
            };
            _command.Parameters.AddRange(new SqlParameter[] { new SqlParameter { ParameterName = "name", Value = name, SqlDbType = SqlDbType.VarChar, Size = 100 },
            new SqlParameter { ParameterName = "email", Value = email, SqlDbType = SqlDbType.VarChar, Size = 50 },
            new SqlParameter { ParameterName = "comment", Value = comment, SqlDbType = SqlDbType.VarChar, Size = 255 },
            new SqlParameter { ParameterName = "website", Value = userWebsite != null ? userWebsite : (object)DBNull.Value, SqlDbType = SqlDbType.VarChar, Size = 20 }});
            _command.Connection.Open();
            int result=_command.ExecuteNonQuery();
            _command.Connection.Close();
            return result;
        }
  1. Muhammad
    April 20, 2015 at 1:32 pm

    Thanks for this article it’s good, but it’s not working for my MS Chart control. If you have any idea about this then, please let me know. My page has a simple MS chart control which needs to be printed as well. When I pass the html of the control to convert, it throws error. Hope you would reply soon. Thanks.

  2. April 21, 2015 at 7:08 am

    Are you trying to convert html to pdf, or something else? Because your comment appeared on a post which is not directly related to html.
    If so then, did you try the sample project ? I can’t say for sure of the error because I don’t know of your html structure. One thing I can say your html should be syntactically correct .

  1. No trackbacks yet.

Leave a reply to Muhammad Hussain Cancel reply