Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Why the error message like "Object reference not set to an instance" comes..

Why the error message like "Object reference not set to an instance" comes..

Scheduled Pinned Locked Moved C#
help
6 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    Samiullah
    wrote on last edited by
    #1

    Hi, I got the error message "object reference not set to an instance". Actually i am doing a small program on DataReader then the above said message comes. Please any suggestions..

    M 1 Reply Last reply
    0
    • S Samiullah

      Hi, I got the error message "object reference not set to an instance". Actually i am doing a small program on DataReader then the above said message comes. Please any suggestions..

      M Offline
      M Offline
      Mogaambo
      wrote on last edited by
      #2

      It seem that you are referencing an object which is not created. post your code.

      S 1 Reply Last reply
      0
      • M Mogaambo

        It seem that you are referencing an object which is not created. post your code.

        S Offline
        S Offline
        Samiullah
        wrote on last edited by
        #3

        private void findbutton_Click(object sender, EventArgs e) { SqlDataReader rdr = null; SqlConnection con = null; SqlCommand cmd = null; try { // Open connection to the database string ConnectionString = "server=INDUS-SERVER;uid=sa;pwd=victory;database=northwind"; con = new SqlConnection(ConnectionString); con.Open(); // Set up a command with the given query and associate // this with the current connection. string CommandText = "SELECT FirstName, LastName" + "FROM Employees" + "WHERE (LastName LIKE @Find)"; cmd = new SqlCommand(CommandText); cmd.Connection = con; // Add LastName to the above defined paramter @Find cmd.Parameters.Add( new SqlParameter( "@Find", // The name of the parameter to map System.Data.SqlDbType.NVarChar, // SqlDbType values 20, // The width of the parameter "LastName")); // The name of the source column // Fill the parameter with the value retrieved // from the text field cmd.Parameters["@Find"].Value = txtFind.Text; // Execute the query rdr = cmd.ExecuteReader(); // Fill the list box with the values retrieved lblFound.Items.Clear(); while (rdr.Read()) { lblFound.Items.Add(rdr["FirstName"].ToString() + " " + rdr["LastName"].ToString()); } } catch (Exception ex) { // Print error message MessageBox.Show(ex.Message); } finally { // Close data reader object and database connection if (rdr != null) rdr.Close(); if (con.State == ConnectionState.Open) con.Close(); }

        V 1 Reply Last reply
        0
        • S Samiullah

          private void findbutton_Click(object sender, EventArgs e) { SqlDataReader rdr = null; SqlConnection con = null; SqlCommand cmd = null; try { // Open connection to the database string ConnectionString = "server=INDUS-SERVER;uid=sa;pwd=victory;database=northwind"; con = new SqlConnection(ConnectionString); con.Open(); // Set up a command with the given query and associate // this with the current connection. string CommandText = "SELECT FirstName, LastName" + "FROM Employees" + "WHERE (LastName LIKE @Find)"; cmd = new SqlCommand(CommandText); cmd.Connection = con; // Add LastName to the above defined paramter @Find cmd.Parameters.Add( new SqlParameter( "@Find", // The name of the parameter to map System.Data.SqlDbType.NVarChar, // SqlDbType values 20, // The width of the parameter "LastName")); // The name of the source column // Fill the parameter with the value retrieved // from the text field cmd.Parameters["@Find"].Value = txtFind.Text; // Execute the query rdr = cmd.ExecuteReader(); // Fill the list box with the values retrieved lblFound.Items.Clear(); while (rdr.Read()) { lblFound.Items.Add(rdr["FirstName"].ToString() + " " + rdr["LastName"].ToString()); } } catch (Exception ex) { // Print error message MessageBox.Show(ex.Message); } finally { // Close data reader object and database connection if (rdr != null) rdr.Close(); if (con.State == ConnectionState.Open) con.Close(); }

          V Offline
          V Offline
          Vimalsoft Pty Ltd
          wrote on last edited by
          #4

          hi Well there are couple of things that you are not doing right in your code. Your comments are interfering with your code. Your code is creaming "Put me inside a Function" You have used unnecessary things in your code. if you can try to write your code like this

              public SqlDataReader GetData()
              {
                  SqlDataReader rd;
                  SqlConnection con;
                  SqlCommand cmd = new SqlCommand();
          
                  string ConnectionString = "server=INDUS-SERVER;uid=sa;pwd=victory;database=northwind";
          
                  con = new SqlConnection(ConnectionString);
          
                  cmd.CommandText = "SELECT FirstName, LastName" + "FROM Employees" + "WHERE (LastName LIKE @Find)";
          
                  cmd.Connection = con;
          
                  cmd.Parameters.Add(new SqlParameter("@Find", SqlDbType.NVarChar, 20, "LastName"));
          
                  cmd.Parameters\["@Find"\].Value = txtFind.Text;
          
                  try
                  {
                      con.Open();
          
                      // Execute the query
                      rd = cmd.ExecuteReader();
                      rd.Close();
          
                      con.Close();
                  }
                  catch (SqlException e)
                  {
                      Messagebox.show(e.Message);
                  }
                  return rd;
              }
          }
          

          }

          Now things are Better, because Previously you just opened the Connection where you were not supposed to, remember that you have to connect to the Database when you want to execute something. after you are done you close it, and now this function returns a reader, then you can iterate through your records or your can just choose to send the data into the datatable and bind the control.

          Vuyiswa Maseko, Sorrow is Better than Laughter, it may Sadden your Face, but It sharpens your Understanding VB.NET/SQL7/2000/2005 http://vuyiswamb.007ihost.com http://Ecadre.007ihost.com vuyiswam@tshwane.gov.za

          S 1 Reply Last reply
          0
          • V Vimalsoft Pty Ltd

            hi Well there are couple of things that you are not doing right in your code. Your comments are interfering with your code. Your code is creaming "Put me inside a Function" You have used unnecessary things in your code. if you can try to write your code like this

                public SqlDataReader GetData()
                {
                    SqlDataReader rd;
                    SqlConnection con;
                    SqlCommand cmd = new SqlCommand();
            
                    string ConnectionString = "server=INDUS-SERVER;uid=sa;pwd=victory;database=northwind";
            
                    con = new SqlConnection(ConnectionString);
            
                    cmd.CommandText = "SELECT FirstName, LastName" + "FROM Employees" + "WHERE (LastName LIKE @Find)";
            
                    cmd.Connection = con;
            
                    cmd.Parameters.Add(new SqlParameter("@Find", SqlDbType.NVarChar, 20, "LastName"));
            
                    cmd.Parameters\["@Find"\].Value = txtFind.Text;
            
                    try
                    {
                        con.Open();
            
                        // Execute the query
                        rd = cmd.ExecuteReader();
                        rd.Close();
            
                        con.Close();
                    }
                    catch (SqlException e)
                    {
                        Messagebox.show(e.Message);
                    }
                    return rd;
                }
            }
            

            }

            Now things are Better, because Previously you just opened the Connection where you were not supposed to, remember that you have to connect to the Database when you want to execute something. after you are done you close it, and now this function returns a reader, then you can iterate through your records or your can just choose to send the data into the datatable and bind the control.

            Vuyiswa Maseko, Sorrow is Better than Laughter, it may Sadden your Face, but It sharpens your Understanding VB.NET/SQL7/2000/2005 http://vuyiswamb.007ihost.com http://Ecadre.007ihost.com vuyiswam@tshwane.gov.za

            S Offline
            S Offline
            Samiullah
            wrote on last edited by
            #5

            Stil i'm getting error..i will do one thing just i will paste all the code.please resolve it... Code: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace DataReaderWith2Tables { public partial class Form1 : Form { private System.Windows.Forms.ListBox lblFound = null; private System.Windows.Forms.Button findButton; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtFind = null; //private System.ComponentModel.Container components = null; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void findbutton_Click(object sender, EventArgs e) { SqlDataReader rdr; SqlConnection con; SqlCommand cmd = new SqlCommand(); string ConnectionString = "server=INDUS-SERVER;uid=sa;pwd=victory;database=northwind"; con = new SqlConnection(ConnectionString); cmd.CommandText = "SELECT FirstName, LastName" + "FROM Employees" + "WHERE (LastName LIKE @Find)"; cmd.Connection = con; cmd.Parameters.Add(new SqlParameter("@Find", System.Data.SqlDbType.NVarChar, 20, "LastName")); cmd.Parameters["@Find"].Value = txtFind.Text; try { con.Open(); rdr = cmd.ExecuteReader(); rdr.Close(); con.Close(); } catch (SqlException ex) { MessageBox.Show(ex.Message); } return rdr; } } }

            A 1 Reply Last reply
            0
            • S Samiullah

              Stil i'm getting error..i will do one thing just i will paste all the code.please resolve it... Code: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace DataReaderWith2Tables { public partial class Form1 : Form { private System.Windows.Forms.ListBox lblFound = null; private System.Windows.Forms.Button findButton; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtFind = null; //private System.ComponentModel.Container components = null; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void findbutton_Click(object sender, EventArgs e) { SqlDataReader rdr; SqlConnection con; SqlCommand cmd = new SqlCommand(); string ConnectionString = "server=INDUS-SERVER;uid=sa;pwd=victory;database=northwind"; con = new SqlConnection(ConnectionString); cmd.CommandText = "SELECT FirstName, LastName" + "FROM Employees" + "WHERE (LastName LIKE @Find)"; cmd.Connection = con; cmd.Parameters.Add(new SqlParameter("@Find", System.Data.SqlDbType.NVarChar, 20, "LastName")); cmd.Parameters["@Find"].Value = txtFind.Text; try { con.Open(); rdr = cmd.ExecuteReader(); rdr.Close(); con.Close(); } catch (SqlException ex) { MessageBox.Show(ex.Message); } return rdr; } } }

              A Offline
              A Offline
              AtulRane
              wrote on last edited by
              #6

              I think you are closing the rdr (rdr.Close()) in try block and then you are trying to return rdr (return rdr). Please check it.

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups