This question already has an answer here:
这个问题在这里已有答案:
- What is a NullReferenceException, and how do I fix it? 31 answers
什么是NullReferenceException,我该如何解决? 31个答案
I have a datatable session
我有一个数据表会话
Session["Items"] = dt;
I am trying to display the count from the session in Site.Master at the top, kind of like on ecommerece websites where they have the Cart at the top.
我试图在Site.Master顶部的会话中显示计数,有点像在ecommerece网站上,他们在顶部有购物车。
I have this, but keep getting null exception error at int count
我有这个,但在int计数时继续得到null异常错误
DataTable dt = (DataTable)Session["Items"];
int count = dt.Rows.Count; //error
if (Session["Items"] == null)
{
if (dt.Rows.Count == 0)
{
lblItems.Text = "Items (0)";
}
else
{
lblItems.Text = "Items" + count;
}
}
3 个解决方案
#1
You should check immediately if Session["Items"]
is NOT null, you do it too late in your code. Try this:
你应该立即检查Session [“Items”]是否为null,你在代码中做得太晚了。试试这个:
DataTable dt = (DataTable)Session["Items"];
if (dt != null)
{
int count = dt.Rows.Count;
if (dt.Rows.Count == 0)
{
lblItems.Text = "Items (0)";
}
else
{
lblItems.Text = "Items" + count;
}
}
else
lblItems.Text = "Items (0)";
#2
There are multiple things that can go wrong and only you can start the debugger and check if:
有很多事情可能出错,只有你可以启动调试器并检查是否:
1) Session["Items"]
is null.
1)Session [“Items”]为空。
2) Session["Items"]
is not a DataTable
. The result of casting it to the DataTable is null in this case.
2)Session [“Items”]不是DataTable。在这种情况下,将其转换为DataTable的结果为null。
3) Session["Items"]
is a DataTable, but it's Rows property is null
3)Session [“Items”]是一个DataTable,但它的Rows属性为null
#3
This should do it for you, since its checking every possible null pointer possibility:
这应该为你做,因为它检查每个可能的空指针的可能性:
DataTable dt = Session["Items"] as DataTable;
dt = dt ?? new DataTable();
int count = dt.Rows == null? 0 : dt.Rows.Count;
lblItems.Text = String.Format("Items ({0})", count);
#1
You should check immediately if Session["Items"]
is NOT null, you do it too late in your code. Try this:
你应该立即检查Session [“Items”]是否为null,你在代码中做得太晚了。试试这个:
DataTable dt = (DataTable)Session["Items"];
if (dt != null)
{
int count = dt.Rows.Count;
if (dt.Rows.Count == 0)
{
lblItems.Text = "Items (0)";
}
else
{
lblItems.Text = "Items" + count;
}
}
else
lblItems.Text = "Items (0)";
#2
There are multiple things that can go wrong and only you can start the debugger and check if:
有很多事情可能出错,只有你可以启动调试器并检查是否:
1) Session["Items"]
is null.
1)Session [“Items”]为空。
2) Session["Items"]
is not a DataTable
. The result of casting it to the DataTable is null in this case.
2)Session [“Items”]不是DataTable。在这种情况下,将其转换为DataTable的结果为null。
3) Session["Items"]
is a DataTable, but it's Rows property is null
3)Session [“Items”]是一个DataTable,但它的Rows属性为null
#3
This should do it for you, since its checking every possible null pointer possibility:
这应该为你做,因为它检查每个可能的空指针的可能性:
DataTable dt = Session["Items"] as DataTable;
dt = dt ?? new DataTable();
int count = dt.Rows == null? 0 : dt.Rows.Count;
lblItems.Text = String.Format("Items ({0})", count);