Search code examples
c#code-behinddatareader

How to handle a NULL value in reader.GetByte(x)?


I've got the following block of code:

//Check to see if the Unique_ID is 10 or 11 and process accordingly
//10 = Both boxes, 11 = Rework only
if (reader.GetByte(16) == 10)
{
   int ES = Convert.ToInt32(reader["ESCALATED"]);
   if (ES == 0)
   {
      chkEscalated.Checked = false;
   }
   else
   {
      chkEscalated.Checked = true;
      chkEscalated.Visible = true;
      lblEscalated.Visible = true;
      chkRework.Visible = true;
      lblRework.Visible = true;
    }
}
else if (reader.GetByte(16) == 11)
{
}
else
{
}

The problem I have is, sometimes, reader.GetByte(16) is NULL. And when that happens, I get an error:

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

I'm still somewhat of a novice, so I'm sure there's something obvious that I'm missing, but I just can't find it.


Solution

  • Use IsDBNull method :

    //Check to see if the Unique_ID is 10 or 11 and process accordingly
    //10 = Both boxes, 11 = Rework only
    if (reader.IsDBNull(16))
    {
       //Add here your code to handle null value
    }
    else
    {
       //Use a switch to read the value only one time
       switch (reader.GetByte(16))
       {
         case 10:
           int ES = Convert.ToInt32(reader["ESCALATED"]);
           if (ES == 0)
           {
              chkEscalated.Checked = false;
           }
           else
           {
              chkEscalated.Checked = true;
              chkEscalated.Visible = true;
              lblEscalated.Visible = true;
              chkRework.Visible = true;
              lblRework.Visible = true;
            }
            break;
    
          case 11:
            break;
    
          default:
            break;
       }
    }