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

  • Thread starter Thread starter Hrithik Gajmal
  • Start date Start date
H

Hrithik Gajmal

Guest
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.

Continue reading...
 
Back
Top