Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
con.Open();
            string s = "select * from " + U_name.Text + " where Physics_Topic= '" + grdTopicname.Text + "'";
            SqlCommand cmd = new SqlCommand(s, con);
            cmd.Connection = con;
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {

                string s1 = "UPDATE " + U_name.Text + " SET ID_Physics=@ID_Physics,Physics_Topic=@Physics_Topic,Physics_score=@Physics_score)";
                SqlCommand cmd1 = new SqlCommand(s1, con);
                cmd1.Parameters.AddWithValue("@ID_Physics", grdID.Text);
                cmd1.Parameters.AddWithValue("@Physics_Topic", grdTopicname.Text);
                cmd1.Parameters.AddWithValue("@Physics_score", Result.Text);
                try
                {
                    cmd1.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    throw new Exception("Error" + ex.Message);

                }
Posted

1.You are executing a data reader, and you cannot execute any command on the current connection by having the data reader open.

2.So you must close the reader then to execute the 2nd command, and is indicated to use try-catch-finally block and to close the reader in finally block!
 
Share this answer
 
Solution1 is also correct, but if you have to have execute the query in the same iteration where you are reading data from data reader then you can go with below solution.

This can happen if you execute a query while iterating over the results from
another query.

This can be easily solved by allowing MARS in your connection string. Add
MultipleActiveResultSets=true to the provider part of your connection string
(where Data Source, Initial Catalog, etc. are specified).
 
Share this answer
 
Comments
iamvinod34 18-Dec-14 1:47am    
Incorrect syntax near ')'.
Line 298: con.Close();
Line 299: }
Line 300: }------>error
Line 301: public string connectionString { get; set; }
Line 302:}
Praveen Kumar Upadhyay 18-Dec-14 1:49am    
what is this?
iamvinod34 18-Dec-14 1:52am    
error came sir,
Incorrect syntax near ')'.
Line 298: con.Close();
Line 299: }
Line 300: }------>error
Line 301: public string connectionString { get; set; }
Line 302:}
Praveen Kumar Upadhyay 18-Dec-14 1:56am    
I can not see your line numbers. So if you are not using loop to read object then close the connection before you execute another query. If you are using loop to read object then use another connection object to execute another query.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900