首页 > 解决方案 > 在页面加载事件 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。

请给我一些见解来解决这个问题,谢谢。

标签: asp.netsql-server

解决方案


推荐阅读