Microsoft Technologies based on the .NET software framework. Miscellaneous topics that do not fit into specific categories.
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.