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

时间:2015-04-01 14:22:03

标签: c# code-behind datareader

我有以下代码块:

//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。当发生这种情况时,我收到一个错误:

  

数据是空的。无法在Null值上调用此方法或属性。

我仍然有点新手,所以我确信有一些明显的东西让我失踪,但我找不到它。

5 个答案:

答案 0 :(得分:2)

使用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;
   }
}

答案 1 :(得分:-1)

如果错过第一个,你真的想读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
   {
   }
}

答案 2 :(得分:-1)

根据您发布的错误消息,似乎有时reader未初始化。 reader是否在某处填充或初始化?如果是,那是一个值得检查的好地方。错误消息只是意味着reader没有引用现有实例,因此它是NULL,因此您无法在其上调用方法,即您无法在其中调用GetByte()

答案 3 :(得分:-1)

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

答案 4 :(得分:-1)

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

试试这个。