我正在从数据库中获取一些数据,并在单击按钮时将其显示在页面上。我希望在不单击任何按钮的情况下自动加载数据,因此我将代码移至页面加载事件,但是executescalar
返回null。这是按钮单击事件中的代码:
namespace bookstore.book
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["connectiondb"].ConnectionString);
conn.Open();
string route = Convert.ToString(Page.RouteData.Values["book"]);
SqlCommand imgcmd = new SqlCommand("select URL from books where name= N'" + route + "'", conn);
SqlCommand head = new SqlCommand("select name from books where name=N'" + route + "'", conn);
SqlCommand authorcmd = new SqlCommand("select author from books where name=N'" + route + "'", conn);
SqlCommand pricecmd = new SqlCommand("select price from books where name=N'" + route + "'", conn);
bookcover.ImageUrl = imgcmd.ExecuteScalar().ToString();
title.InnerText = head.ExecuteScalar().ToString();
author.InnerText = "نویسنده: " + authorcmd.ExecuteScalar().ToString();
author.InnerText = "قیمت: " + authorcmd.ExecuteScalar().ToString();
}
}
}
这是向上移动到页面加载事件的代码:
namespace bookstore.book
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["connectiondb"].ConnectionString);
conn.Open();
string route = Convert.ToString(Page.RouteData.Values["book"]);
SqlCommand imgcmd = new SqlCommand("select URL from books where name= N'" + route + "'", conn);
SqlCommand head = new SqlCommand("select name from books where name=N'" + route + "'", conn);
SqlCommand authorcmd = new SqlCommand("select author from books where name=N'" + route + "'", conn);
SqlCommand pricecmd = new SqlCommand("select price from books where name=N'" + route + "'", conn);
bookcover.ImageUrl = imgcmd.ExecuteScalar().ToString();
title.InnerText = head.ExecuteScalar().ToString();
author.InnerText = "نویسنده: " + authorcmd.ExecuteScalar().ToString();
author.InnerText = "قیمت: " + authorcmd.ExecuteScalar().ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
}`
页面加载事件中出现的错误:
System.NullReferenceException:'对象引用未设置为 对象的实例。'
System.Data.Common.DbCommand.ExecuteScalar(...)返回null。
请给我一些解决此问题的见识,谢谢。