0

I have a code which gives me error as

Data is Null. This method or property cannot be called on Null values

if (reader.Read())
            {
                return reader.GetString(0);
            }
            return null;

Below is the full code

[WebMethod]
public static string GetCurrentToBin(string ToBin, int warehouseId)
{
    var connectionString = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();
    using(var conn = new SqlConnection(connectionString))
    {
         const string queryString = "exec sp_P_WMS_Stock_Adj_Validation_Proc @Bin , @warehouse";

            var sqlCommand = new SqlCommand(queryString , conn);
            sqlCommand.Parameters.AddWithValue("@Bin",ToBin);
            sqlCommand.Parameters.AddWithValue("@warehouse", warehouseId);

            conn.Open();
            var reader = sqlCommand.ExecuteReader();

            if (reader.Read())
            {
                return reader.GetString(0);
            }
            return null;
     }
}
Nad
  • 4,605
  • 11
  • 71
  • 160

2 Answers2

0

You can try it for null values like

if(!reader.IsDBNull(0))
  return reader.GetString(0);

Or use the method below

public string GetString(SqlDataReader reader, int columnIndex)
{
   if(!reader.IsDBNull(columnIndex))
       return reader.GetString(columnIndex);
   return string.Empty;
}

like this

return GetString(reader, 0);
Ali Baig
  • 3,819
  • 4
  • 34
  • 47
0

You should check with IsDBNull first.

For example see msdn https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.isdbnull.aspx

kauzu
  • 21
  • 4