C# – System.InvalidOperationException: ExecuteReader: Connection property has not been initialized

.netasp.netc++executereader

protected void Button3_Click(object sender, EventArgs e)
{
 cn.Open();

 SqlCommand cmd = new SqlCommand("select top '"+Label4.Text+"' * from qb_vb where marks=1");

 SqlDataReader dr1 = cmd.ExecuteReader();

if (dr1.Read())
 {
  Label8.Text = dr1["quest"].ToString();
  Label9.Text = dr1["ans1"].ToString();
 }
cn.Close();

}

Best Solution

You need to associate the command with the connection you opened:

cn.Open();
SqlCommand cmd = new SqlCommand("select top '"+Label4.Text+"' * from qb_vb where marks=1");
cmd.Connection = cn; // <------ THIS MUST BE ADDED
SqlDataReader dr1 = cmd.ExecuteReader();
if (dr1.Read())
{
    Label8.Text = dr1["quest"].ToString();
    Label9.Text = dr1["ans1"].ToString();
}
cn.Close();