【问题标题】:Object reference not set to an instance of an object While trying to Update data with the help of database [duplicate]对象引用未设置为对象的实例尝试借助数据库更新数据时[重复]
【发布时间】:2019-08-02 09:55:59
【问题描述】:

我正在创建一个图书网站,我创建了一个图书页面,当我单击该链接时,我在其中给出了编辑图书页面链接,应根据数据库中的图书 ID 打开更新表单,并且应填写更新表单使用数据库中预先输入的详细信息。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WEbApp
{
    public partial class Edit_Books : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="ConnectionString";Integrated Security=True");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }
            con.Open();
            int id = Convert.ToInt32(Request.QueryString["bkid"].ToString());

            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from Books where bkid="+id+"";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            foreach(DataRow dr in dt.Rows)
            {
                Textbox1.Text = dr["book_name"].ToString();
                Textbox2.Text = dr["book_author"].ToString();
                Textbox3.Text = dr["book_publication"].ToString();

            }
        }
    }
}

当我运行上面的代码时,我在这一行得到一个错误:

int id = Convert.ToInt32(Request.QueryString["bkid"].ToString());
Object reference not set to an instance of an object.

【问题讨论】:

    标签: c# asp.net sql-server database project-management


    【解决方案1】:

    听起来Request.QueryString 不包含bkid 的条目?

    把代码改成这样:

    var bkId = Request.QueryString["bkid"];
    int id = Convert.ToInt32(bkId.ToString());
    

    使用调试器检查 bkId 的值 - 我怀疑它会是 null

    【讨论】:

    • 当书籍页面打开时,它会显示所有书籍数据和一个更新按钮,当我单击更新按钮时,它会获取该书籍的 ID 并将用户重定向到编辑书籍页面。但在这种情况下,一切都会持续到点击按钮时,它会在搜索栏中的链接中显示 id,但页面显示错误。
    • 在这种情况下,确定将int id 更改为int? id 会更好吗?
    • 问题是bkId 为空。 id 永远不会被分配,因为Convert.ToInt32 会抛出异常。
    • 尝试替换代码仍然得到相同的错误。我指的是这个视频:youtu.be/yM9Y7NMxC28 我想做他正在做的同样的事情来编辑书籍。请观看视频并告诉我该怎么做。
    • 如果你看过视频可以帮帮我吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 2010-09-12
    • 2020-11-03
    相关资源
    最近更新 更多