It looks like you try to use the reader before you open the connection.
string s = "select * from "+U_name.Text+" where Physics_Topic='"+grdTopicname.Text+"'";
con.Open();
SqlCommand cmd = new SqlCommand(s, con);
cmd.Connection = con;
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
dr.Read();
string s1 = "update " + U_name.Text + " set TopicID='" + grdID.Text + "',Physics_Topic='" + grdTopicname.Text + "',Physics_score='"+Result.Text+"'";
cmd.ExecuteNonQuery();
}
else
{
string s2 = "insert into" + U_name.Text + "where TopicID='" + grdID.Text + "',Physics_Topic='" + grdTopicname.Text + "',Physics_score='" + Result.Text + "'";
cmd.ExecuteNonQuery();
con.Close();
That said, there are a few things you should correct in your code.
1. Use
using
statements for connections. It will automatically close your connection.
using (SqlConnection con = new SqlConnection(connectionString))
{
}
2. Also use
using
for readers for the same reason
using (SqlDataReader dr = cmd.ExecuteReader())
{
}
3. Use paramterized SQL commands
This makes your life easier when it comes to change the SQL commands and it prevents from injection of malicious code.
SqlCommand.Parameters[
^]