Share via

Issue with the connection

Peter Liang 3,266 Reputation points
2026-03-02T08:48:58.8766667+00:00

Hi,

I got the issue like

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

on the last line below. Any help?

User's image

Developer technologies | .NET | Other

Answer accepted by question author
  1. Jack Dang (WICLOUD CORPORATION) 15,870 Reputation points Microsoft External Staff Moderator
    2026-03-03T06:57:29.04+00:00

    Hi @Peter Liang ,

    Thanks for reaching out.

    The error ExecuteScalar requires an open and available Connection. The connection's current state is closed appears when the SqlCommand doesn’t know which database connection to use, or the connection isn’t open when the command runs.

    One way to fix this is to make sure your command is linked to an open connection and use using blocks so the connection is managed safely. For example:

    int cnt5 = 0;
    
    if (string.IsNullOrWhiteSpace(tb_cust_code.Text))
    {
        MessageBox.Show("Please enter a customer code");
        return;
    }
    
    using (SqlConnection conn = new SqlConnection(yourConnectionString))
    {
        conn.Open();
    
        using (SqlCommand cmd5 = new SqlCommand(
            "SELECT COUNT(*) FROM customer3 WHERE No_=@custcode",
            conn
        ))
        {
            cmd5.Parameters.Add("@custcode", SqlDbType.VarChar).Value = tb_cust_code.Text;
            cnt5 = (int)cmd5.ExecuteScalar();
        }
    }
    
    MessageBox.Show($"Matching rows: {cnt5}");
    

    You can take this snippet as a reference and adjust it to fit your project’s structure.

    Hope this helps! If my answer was helpful - kindly follow the instructions here so others with the same problem can benefit as well.


1 additional answer

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.