Web应用程序中的导航错误

时间:2014-01-29 03:33:11

标签: c# asp.net database

我只是这个程序语言的新手,我做了一个关于它的迷你项目。任何人都可以告诉我,我会为这个错误做些什么吗?!首先它运作良好,但当我单击其他选项卡时,它将不会处理,这将是错误..

enter image description here

Class1 ob = new Class1();
ob.dt = (DataTable)Session["cart"];
string str = "";

if (ob.dt.Rows.Count == 0 )
{
    str = "_______________________________";

    ListBox1.Items.Add(str);
    str = "No Item Selected";
    ListBox1.Items.Add(str);
    str = "_______________________________";
    ListBox1.Items.Add(str);
}
else
{
    str = "    " + "Product  " + "Quantity";
    ListBox1.Items.Add(str);
    str = "_______________________________";
    ListBox1.Items.Add(str);
    int index = 1;

    for (int j = 0; j <= ob.dt.Rows.Count - 1; j++)
    {
        DataRow dr = ob.dt.Rows[j];
        str = Convert.ToString(index) + ". " + Convert.ToString(dr["pname"]) 
        +"" + Convert.ToString(dr["qty"]);
        ListBox1.Items.Add(str);
        index++;
    }
    int total = Class2.gettotalprice();

    str = "_______________________________";
    ListBox1.Items.Add(str);
    str = "Total Amount=  " + total.ToString();

    ListBox1.Items.Add(str);
}

将数据更改为非null后,将再次出现此行中出现的新错误

for (int j = 0; j <= ob.dt.Rows.Count - 1; j++)
{
    DataRow dr = ob.dt.Rows[j];
    str = Convert.ToString(index) + ". " + Convert.ToString(dr["pname"]) 
    +"" + Convert.ToString(dr["qty"]);
    ListBox1.Items.Add(str);
    index++;
}

看一下这个截图

enter image description here

2 个答案:

答案 0 :(得分:1)

您应该始终检查以确保您操作的对象不为空。

如果您将条件替换为下面的条件,这将阻止您在该行上获得空引用错误:

if (ob != null && ob.dt != null && ob.dt.rows != null && ob.dt.rows.Count == 0)

您的obdt对象为null。查找要分配这些对象的代码行或设置它们并查看它们为null的原因。当它们为null时,您无法调用该对象的方法或访问属性,因为您没有该类的实例。在代码中的某处,您将obdt设置为null。或者你永远不会实例化它们,但我怀疑是这样。它看起来更像是您没有从您尝试访问的存储库或其他东西返回任何记录。

编辑:

您正在看第二个问题,因为您再次检查没有NULL对象。你可以将你的for循环包装在一个空的检查中,但我不能告诉你程序中的任何地方你必须进行空检查。

if (ob != null && ob.dt != null && ob.dt.rows != null)
 {
          for (int j = 0; j <= ob.dt.Rows.Count - 1; j++)
            {
                DataRow dr = ob.dt.Rows[j];
                str = Convert.ToString(index) + ". " + Convert.ToString(dr["pname"]) 
            +"" + Convert.ToString(dr["qty"]);
                ListBox1.Items.Add(str);
                index++;
            }
 }

答案 1 :(得分:0)

在使用之前首先检查数据是否为空,如下所示:

if (ob.dt == null)
{
    //handle here
    return;
}

//and your code goes here
if (ob.dt.Rows.Count == 0 )
{
    str = "_______________________________";

    ListBox1.Items.Add(str);
    str = "No Item Selected";
    ListBox1.Items.Add(str);
    str = "_______________________________";
    ListBox1.Items.Add(str);
}
.....