每当我直接访问我的页面时(mypage.aspx),它都会返回错误:
对象未设置为未设置为对象实例的对象。
如果我添加一个查询字符串(mypage.aspx?sr = true)它可以正常工作,但我正在检查以确保它在评估它有一个值之前,它应该没有值。那么为什么我直接访问页面时会出现错误?
if (!IsPostBack)
{
string qu1 = "";
string qu2 = "";
string qu3 = "";
if (Request.QueryString["qu1"] != null)
{
qu1 = Request.QueryString["qu1"].ToString();
if (qu1 != "")
{
qu1DropDownList.SelectedValue = industry;
}
}
if (Request.QueryString["qu2"] != null)
{
qu2 = Request.QueryString["qu2"].ToString();
if (qu2 != "")
{
qu2DropDownList.SelectedValue = category;
}
}
fillDropDownList();
if (Request.QueryString["qu3"] != null)
{
qu3 = Request.QueryString["qu3"].ToString();
if (qu3 != "")
{
qu3tDropDownList.SelectedValue = product;
}
}
}
string search = "";
string qu1value = IndustryDropDownList.SelectedValue;
string qu2value = ProductCategoryDropDownList.SelectedValue;
string qu3value = ProductDropDownList.SelectedValue;
using (SPSite site = new SPSite("SITE"))
using (SPWeb oWebsiteRoot = site.OpenWeb())
{
SPList oList = oWebsiteRoot.Lists["SpacesInfo"];
SPListItemCollection items = null;
if (Request.QueryString["sr"] != "" && Request.QueryString["sr"] != null)
{
search = Request.QueryString["sr"].ToString();
if (search == "true")
{
if (indvalue == "select" & catvalue == "select")
{
items = oList.Items;
}
else if (indvalue != "select" & catvalue != "select" & provalue != "select")
{
SPQuery query = new SPQuery();
query.Query = "MYQUERY";
items = oList.GetItems(query);
}
else if (indvalue != "select" & catvalue != "select" & provalue == "select")
{
SPQuery query = new SPQuery();
query.Query = "MYQUERY";
items = oList.GetItems(query);
}
else if (indvalue != "select" & catvalue == "select")
{
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Industry' /><Value Type='Choice'>" + indvalue +
"</Value></Eq></Where>";
items = oList.GetItems(query);
}
else if (indvalue == "select" & catvalue != "select" & provalue == "select")
{
SPQuery query = new SPQuery();
query.Query = "MYQUERY";
items = oList.GetItems(query);
}
else if (indvalue == "select" & catvalue != "select" & provalue != "select")
{
SPQuery query = new SPQuery();
query.Query = "MYQUERY";
items = oList.GetItems(query);
}
else
{
errorLabel.Text = "Please contact the administrator.";
items = oList.Items;
}
}
else
{
items = oList.Items;
}
}
DataTable table = new System.Data.DataTable();
table = items.GetDataTable();
spacerepeater.DataSource = table;
spacerepeater.DataBind();
}
答案 0 :(得分:0)
更改此if语句的顺序:
if (Request.QueryString["sr"] != "" && Request.QueryString["sr"] != null)
应该是
if (Request.QueryString["sr"] != null && Request.QueryString["sr"] != "")
问题在于,在您的代码中,它会查找空字符串(“”)并因为对象为null而失败。在我的版本中,它将看到值为null并且在没有检查第二个的情况下从if语句中失败。
这通常被称为短路评估。
答案 1 :(得分:0)
使用:
if (!String.IsNullOrEmpty(Request.QueryString["sr"]))
{
//Do stuff
}