Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 动态创建复选框时出现异常_C#_Nullreferenceexception - Fatal编程技术网

C# 动态创建复选框时出现异常

C# 动态创建复选框时出现异常,c#,nullreferenceexception,C#,Nullreferenceexception,以下是我在运行时创建复选框的代码: if (reader.HasRows) { while (reader.Read()) { CheckBox xb = new CheckBox(); xb.Text = reader["AnalysisGroup"].ToString(); xb.Name =

以下是我在运行时创建复选框的代码:

if (reader.HasRows)
            {
                while (reader.Read())
                {
                   CheckBox xb = new CheckBox();
                   xb.Text = reader["AnalysisGroup"].ToString();
                   xb.Name = reader["AnalysisGroup"].ToString();
                   xb.SetBounds(100,50, 200, 10);
                   panel1.Controls.Add(xb);                        
                }
            }
我在运行此代码时遇到异常:

对象引用未设置为对象的实例

为什么会发生这种情况?我确信读卡器有行,并且我测试了问题在于添加控制代码。

myReader[“AnalysisGroup”]
可以为空,请执行以下操作

if (myReader["AnalysisGroup"] != DBNull.Value)
{
    string val = reader["AnalysisGroup"].ToString();
    CheckBox xb = new CheckBox();
    xb.Text = val;
    xb.Name = val;
    xb.SetBounds(100, 50, 200, 10);
    panel1.Controls.Add(xb);
}

它在哪个对象上抛出异常?我认为这仍然会抛出异常,如果值真的
==DbNull.value
.ToString()
不会失败。你需要使用(你可以通过获取索引)reader的值不是null,我通过MessageBox弹出它的内容来测试它