tags:

views:

613

answers:

3
        private void button1_Click(object sender, EventArgs e)
    {
        string name;
        name = textBox5.Text;
        SqlConnection con10 = new SqlConnection("con strn");
        SqlCommand cmd10 = new SqlCommand("select * from sumant where username=@name");
        cmd10.Parameters.AddWithValue("@name",name);
        cmd10.Connection = con10;
        cmd10.Connection.Open();//line 7
        SqlDataReader dr = cmd10.ExecuteReader();


    }

    if ( textBox2.Text == dr[2].ToString())
        {//do something;
         }

when i debug till line 7,its k but after that dr throes an exception: Invalid attempt to read when no data is present. thats nt poss as i do have data in table with username=sumant. pl tell whether the 'if' statement is correct or not.........

and how do i remove the error??

thanx!!

A: 

You have to call dr.Read() before attempting to read any data. That method will return false if there is nothing to read.

Colin Mackay
+1  A: 

You have to call DataReader.Read to fetch the result:

SqlDataReader dr = cmd10.ExecuteReader();
dr.Read();
// ...

DataReader.Read returns a boolean, so if you have more than 1 result, you can do:

While (dr.Read()) {
  // read data for each record here
}
Julien Poulin
A: 

oops, forgot to read the datareader...... cheers!!

knowledgehunter