如何处理 reader.GetByte(x) 中的 NULL 值?

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

我得到了以下代码块:

//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
{
}

我遇到的问题是,有时 reader.GetByte(16) 为 NULL。当发生这种情况时,我得到一个错误:

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

我还是个新手,所以我确定我缺少一些明显的东西,但我就是找不到。

如果你错过了第一个 if,你真的要读 2 遍吗? 也许这就是问题所在。 将值存储为 var a = reader.GetByte(16) 并查找该值。 像这样:

//Check to see if the Unique_ID is 10 or 11 and process accordingly
//10 = Both boxes, 11 = Rework only 
var a = reader.GetByte(16);
if(a != null)
{
   if (a == 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 (a == 11)
   {
   }
   else
   {
   }
}

根据您发布的错误消息,似乎有时 reader 未初始化。 reader 是否在某处被填充或初始化?如果是,那是检查的好地方。错误消息仅表示 reader 未引用现有实例,因此它为 NULL,因此您不能对其调用方法,即您不能在其中调用 GetByte()

你可以在if语句中添加if (reader.GetByte(16) != null && reader.GetByte(16) == 10) 这将检查 reader.GetByte(16) 是否为 null

if(!String.IsNullOrEmpty(reader.GetByte(16).ToString()))
{
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
{
}
}

试试这个。

使用IsDBNull方法:

//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;
   }
}