Shakir Nasser
Shakir Nasser

Reputation: 43

object reference not set to an instance of an object asp.net

In the below code, when I press button2 it says:

object reference not set to an instance of an object

What's going on?

public partial class rec : System.Web.UI.Page
{
   protected void Button1_Click(object sender, EventArgs e)
   {
      try
      {
          SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|DB.mdf;Integrated Security=True;User Instance=True");

          SqlCommand cmd;
          con.Open();

          cmd = new SqlCommand("SELECT  SrviceType, Msg FROM OrderNum ", con);

          SqlDataReader dr;
          dr = cmd.ExecuteReader();

          dr.Read();

          Label1.Text = dr[0].ToString();
          TextBox1.Text = dr[1].ToString();
      }
      catch (Exception ex)
      {
          System.Windows.Forms.MessageBox.Show(ex.Message);
      }
  }

  protected  void Button2_Click(object sender, EventArgs e)
  {
      SqlDataReader dr = null;

      try
      {
          dr.Read();
          Label1.Text = dr[0].ToString();
          TextBox1.Text = dr[1].ToString();
      }
      catch (Exception ex)
      {
          System.Windows.Forms.MessageBox.Show(ex.Message);
      }
  }
}

Upvotes: 2

Views: 30345

Answers (3)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26199

SqlDataReader object is used to hold the one time result of executed/fetched data from the database.which can be used to iterate over each row to get the required columns. hence before Trying to read from SqlDataReader object it should have some data.

which can be accomplished by following statement:

SqlDataReader sqldatareaderobject=sqlcommandobject.ExecuteReader();

you are following this above principle in Button1_click function but you are missing the same principle in Button2_click function.

SqlDataReader object in your case "dr" contains null as you have missed to call the ExecuteReader() function, and it is throwing exception as you are calling Read() function on top of null object(dr).

Thank you

Upvotes: 1

Mudeyanse
Mudeyanse

Reputation: 48

SqlDataReader dr = null;

Then you try to read from null object from

dr.Read();

Make sure this is web page you can not keep the state if you want to get the Button_click1 data rearder

Upvotes: 3

Jerry
Jerry

Reputation: 4408

You need to assign the reader dr to a command.

Take a look at the example here: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx

Upvotes: 1

Related Questions