none
System.NullReferenceException: 'Object reference not set to an instance of an object.' RRS feed

  • Question

  • I am creating a book website in which there is page all book which shows all books with edit button when clicked on that it redirects to the edit form with id parameter but when i try to retrieve data from database to fill the textbox it shows me the error:

    System.NullReferenceException: 'Object reference not set to an instance of an object.'

    bkId was null.

    This is my aspx.cs code:

    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 BibiloManiac
    {
        public partial class Edit_Books : System.Web.UI.Page
        {
            SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Hrithik Gajmal\source\repos\BibiloManiac\BibiloManiac\App_Data\BibiloManiac.mdf;Integrated Security=True");
            protected void Page_Load(object sender, EventArgs e)
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
                con.Open();

                var bkId = Request.QueryString["bkid"];
                int id = Convert.ToInt32(bkId.ToString());
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select bkid 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)
                {
                    bookname.Text = dr["bookname"].ToString();
                }
             }
        }
    }

    Please help me clear this error fast as possible.


    Friday, August 2, 2019 4:32 PM

Answers

All replies

  • If the parameter is called “id”, then try var bkId = Request.QueryString["id"].

    Friday, August 2, 2019 6:28 PM
  • Thanks Sir it Worked.

    Can you just help me some more things like here i used this command to retrieve book name from database:bookname.Text = dr["bookname"].ToString();

    Like that i have used checkboxlist to store book categories in one single cell with "/" separator i have written this to retrieve checkboxlist selected  items: bkcategories.Text=dr["bookcategories"].ToString();

    When i select a book to edit with single checkbox selected it shows properly the selected item in checkboxlist but when i select a book to edit with multiple categories selected it shows me an error.

    Once again thanks for the help.




    Saturday, August 3, 2019 6:55 AM