asp.net - 在页面加载事件 asp.net 上未获取数据
问题描述
我正在从数据库中获取一些数据并在单击按钮时将它们显示在页面上。我希望在不单击任何按钮的情况下自动加载数据,因此我将代码移至页面加载事件但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。
请给我一些见解来解决这个问题,谢谢。
解决方案
推荐阅读
- security - 为什么要在 XSS 预防中将 & 转换为 & ?
- css - 如何在 Polymer 2 中正确导入 Material Design Iconic Font?
- java - Apache tika 将 docx 文件中的嵌入式 word pad 文件转换为 .bin 文件
- ios - 使用 segue 导航到另一个控制器
- laravel - 如何在 Laravel 的 Sqlite 中注册一个函数?
- linux - ERRR:无法从 baseport = 54321 找到 /168.2.4.54 的空闲端口
- azure - VMExtensionProvisioningError:超时
- python - 将嵌入在 C 中的 Word2Vec 转换为 Python 的 Gensim Word2vec
- javascript - 节点服务器,html输入null
- reactjs - Redux Thunk:动作必须是普通对象