Search code examples
c#datareader

How to avoid Tostring exception if string is null?


I want to convert the data row value to sring as follows.

userGuid = dr["user_guid"].ToString();

It may contains Guid or null(Not string empty). If it contains null i got the exception.

How can i overcome this..


Solution

  • I guess you are reading from data reader.

    You will have to check if the value is null or DBNull and then you can call to string method.

        string user_guid = dr["user_guid"] != DBNull.Value && dr["user_guid"] != null ? dr["user_guid"].ToString() : null ; 
    

    Hope this helps.