Thursday, 16 August 2012

.Net Beginners : Object cannot be cast from DBNull to other types Error

This error occurred due to cast or convert or assign NULL value cell of data row or data table.

Error Reason :

Here is example for this.
We have datatable. This data table contains value of cusutomers, thsi data table has three columns.
Columns are customer_id, customer_firstname and customer_lastname.
Sometimes customer_lastname column has DBNULL value and we directly assign this value to string variable at that time this error occured.

Something like this.
dtCustomer.rows[0]["customer_lastname "]  has DBNULL value. and we are assigning this value to variable like this.

C# Examples :
string strCustomerLastName = dtCustomer.Rows[0]["customer_lastname "].ToString(); Examples :
Dim strCustomerLastName As String = dtCustomer.Rows(0)("customer_lastname ").ToString()

At this time this error occured.

Solution :

Before assigning or converting this DBNULL value we have make check for this.
We can make check with "System.DBNull.Value" value. We compare both "cell" and "System.DBNull.Value" value if both are same so we do not assign or convert that value. We simply use default value.

Here is Example for this.

C# Examples :
        string strCustomerLastName=string.Empty;
        if(dtCustomer.Rows[0]["customer_lastname "] != System.DBNull.Value)
            strCustomerLastName = dtCustomer.Rows[0]["customer_lastname "].ToString();
        } Examples :
        Dim strCustomerLastName As String = String.Empty
        If (dtCustomer.Rows(0)("customer_lastname ") IsNot System.DBNull.Value) Then
            strCustomerLastName = dtCustomer.Rows(0)("customer_lastname ").ToString()
        End If

This is very useful articles for Beginning .Net .

This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.

No comments:

Post a Comment