Click here to Skip to main content
15,890,506 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I got the below error

"ExecuteReader requires an open and available Connection. The connection's current state is closed"

I'm trying to do the coding for the auto-increment serial numbers. Please help me to clear this error.

What I have tried:

class Generator
    {
        public static void autoincrement(string sqlquery, Control textbox)
        {
            SqlConnection con = Connection.GetConnection();
            con.Open();
            SqlCommand cmd = new SqlCommand(sqlquery, Connection.GetConnection());
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                string value = dr[0].ToString();
                if (value == "")
                {
                    textbox.Text = "111";
                }
                else
                {
                    textbox.Text = dr[0].ToString();
                }
            }
            
            con.Close();

        }
    }
Posted
Updated 6-Dec-20 21:49pm

1 solution

Look at your code: You create a connection:
C#
SqlConnection con = Connection.GetConnection();
You open it:
C#
con.Open();
And you then ignore it and create another:
C#
SqlCommand cmd = new SqlCommand(sqlquery, Connection.GetConnection());

Use the one you just opened, and it'll work:
C#
SqlCommand cmd = new SqlCommand(sqlquery, con);


I'd strongly suggest that you look at using blocks though - they ensure teh connection is correctly closed and disposed when you are finished with it:
C#
using (SqlConnection con = Connection.GetConnection())
   {
   con.Open();
   using (SqlCommand cmd = new SqlCommand(sqlquery, con))
      {
      using (SqlDataReader dr = cmd.ExecuteReader())
         {
         if (dr.Read())
            {
            string value = dr[0].ToString();
            if (string.IsNullOrWhitespace(value))
               {
               textbox.Text = "111";
               }
            else
               {
               textbox.Text = value;
               }
            }
        }
    }
 
Share this answer
 
Comments
ishuishika 7-Dec-20 4:28am    
Thank you so much it helped me. I'm really thankful to u.
OriginalGriff 7-Dec-20 4:57am    
You're welcome!

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