我遇到了nullpointer的问题。我似乎无法理解为什么我的代码是错误的。任何帮助将不胜感激。这是我的代码:
protected void Page_Load(object sender, EventArgs e)
{
Product aProd = new Product();
// Get Product ID from querystring
string prodID = Request.QueryString["ProdID"].ToString(); (null pointer occurs at this line. )
prod = aProd.getProduct(prodID);
//Display product details on web form
lbl_ProdName.Text = prod.Product_Name;
lbl_ProdDesc.Text = prod.Product_Desc;
lbl_Price.Text = prod.Unit_Price.ToString("c");
img_Product.ImageUrl = "~\\Images\\" + prod.Product_Image;
//Store the value in invisible fields
lbl_Price.Text = prod.Unit_Price.ToString();
lbl_ProdID.Text = prodID.ToString();
}
这些是Product.cs的代码。我仍然不知道我的代码出错了
public class Product
{
string _connStr = ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString;
private string _prodID = null;
private string _prodName = string.Empty;
private string _prodDesc = ""; // this is another way to specify empty string
private decimal _unitPrice = 0;
private string _prodImage = "";
private int _stockLevel = 0;
// Default constructor
public Product()
{
}
// Constructor that take in all data required to build a Product object
public Product(string prodID, string prodName, string prodDesc,
decimal unitPrice, string prodImage, int stockLevel)
{
_prodID = prodID;
_prodName = prodName;
_prodDesc = prodDesc;
_unitPrice = unitPrice;
_prodImage = prodImage;
_stockLevel = stockLevel;
}
// Constructor that take in all except product ID
public Product(string prodName, string prodDesc,
decimal unitPrice, string prodImage, int stockLevel)
: this(null, prodName, prodDesc, unitPrice, prodImage, stockLevel)
{
}
// Constructor that take in only Product ID. The other attributes will be set to 0 or empty.
public Product(string prodID)
: this(prodID, "", "", 0, "", 0)
{
}
// Get/Set the attributes of the Product object.
// Note the attribute name (e.g. Product_ID) is same as the actual database field name.
// This is for ease of referencing.
public string Product_ID
{
get { return _prodID; }
set { _prodID = value; }
}
public string Product_Name
{
get { return _prodName; }
set { _prodName = value; }
}
public string Product_Desc
{
get { return _prodDesc; }
set { _prodDesc = value; }
}
public decimal Unit_Price
{
get { return _unitPrice; }
set { _unitPrice = value; }
}
public string Product_Image
{
get { return _prodImage; }
set { _prodImage = value; }
}
public int Stock_Level
{
get { return _stockLevel; }
set { _stockLevel = value; }
}
答案 0 :(得分:0)
Request.QueryString["ProdID"]
返回null。
因此,ToString()
来电会导致System.NullPointerException
解决方案:确保您的Request.QueryString["ProdID"]
来电回复正确的对象,或自行测试结果:
var obj = Request.QueryString["ProdID"];
string prodID = obj == null ? String.Empty : obj.ToString();