-3

I am learning to use select query for my program .

This my code.

con.Open();

SqlCommand cmd = new SqlCommand("select id from qw where name='" + TextBox1.Text + "'", con);
SqlDataReader dr = SqlDataReader();
dr = cmd.ExecuteReader();
dr.read();
TextBox2.Text = dr[0].Tostring();
dr.close();
con.Close();

it show this error message

'System.Data.SqlClient.SqlDataReader' is a 'type' but is used like a 'variable'

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Balaji
  • 25
  • 7

1 Answers1

3

That's the correct code that match yours above

using(SqlConnection con = new SqlConnection(.......))
using(SqlCommand cmd = new SqlCommand("select id from qw where name=@name", con))
{
    con.Open();
    cmd.Parameters.AddWithValue("@name", TextBox1.Text);
    using(SqlDataReader dr = cmd.ExecuteReader())
    {
       if(dr.read())
       {
           TextBox2.Text = dr[0].ToString();
       }
    }
}

Things changed:

  • Use the using statement around disposable objects (so they are disposed and closed when no more needed and also in case of exceptions)
  • Use a parameterized query instead of string concatenation (read about Sql Injection)
  • Get the reader executing ExecuteReader method of your command
  • Check if the reader returns something
Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286