samedi 9 mai 2015

asp.net error Object reference not set to an instance of an object when I retrieve records from database

I'm trying to retrieve records from SQL database, but the returned value is NULL. I debugged it and I discovered that the returned DataTable is null

Here is the code of Database class

    public DataTable ModelOfBookProfileElements(int id)
    {


        String Query = string.Format("SELECT Book_Name,Book_Author,Book_Description FROM Book WHERE Book_ID = {0}",id);

        return RunQuering(Query);


    }



    public DataTable RunQuering(String Query)
   {

       table = new DataTable();
       cmd.CommandType = CommandType.Text;
       cmd.CommandText = Query;
       table.Load(cmd.ExecuteReader());

       return table;

   }

the code of in .ascx.cs file

      protected void Page_Load(object sender, EventArgs e)
    {
        Book book = new Book();
        if (Session["Student"] == null)
        {
            Response.Redirect("LoginSite.aspx");
        }
        else
        {
            DataTable bookdata = new DataTable();
            string id = Request.QueryString["id"];

             int index = Convert.ToInt32(id);
           bookdata = book.GetModelOfBookProfileElements(index);
           if (bookdata.Rows.Count > 0)
           {


               for (int i = 0; i < bookdata.Rows.Count; i++)
               {
                   Label1.Text = bookdata.Rows[i][0].ToString();
                   Label2.Text = bookdata.Rows[i][1].ToString();
                   Label4.Text = bookdata.Rows[i][2].ToString();
               }
           }


        }
    }

in book class

    public DataTable GetModelOfBookProfileElements(int id)
   {

       DB = Database.DB_Object();
       DB.OpenConnection();



       DB.ModelOfBookProfileElements(id);

       DB.CloseConnection();
       return table;
   }

Aucun commentaire:

Enregistrer un commentaire