C# – ExecuteNonQuery requires an open and available Connection. The connection’s current state is closed

csql

My Code :

public bool Insertcustomer()
{
    try
    {
        SqlCommand cmd = new SqlCommand("Insertcustomermaster", dal.con);
        cmd.Parameters.Add("@customercode", SqlDbType.Int).Value = customercode;
        cmd.Parameters.Add("@customername", SqlDbType.NChar).Value = customername;
        cmd.Parameters.Add("@address1", SqlDbType.NChar).Value = address1;
        cmd.Parameters.Add("@address2", SqlDbType.NChar).Value = address1;
        cmd.Parameters.Add("@phoneno", SqlDbType.Int).Value = phoneno;
        cmd.Parameters.Add("@mobileno", SqlDbType.Int).Value = mobileno;
        cmd.Parameters.Add("@mailid", SqlDbType.NChar).Value = mailid;
        cmd.Parameters.Add("@website", SqlDbType.NChar).Value = website;
        cmd.Parameters.Add("@occupation", SqlDbType.NChar).Value = occupation;
        cmd.Parameters.Add("@status", SqlDbType.Bit).Value = status;


        cmd.CommandType = CommandType.StoredProcedure;
        return Convert.ToBoolean(cmd.ExecuteNonQuery());  //Error
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

App Config :

im new in c# .net..im not able to find this error..anybody help..

Best Answer

You should open the connection and close it .

string connectionString = "";
SqlConnection con = new SqlConnection(connectionString);
con.Open();

//do your coding 
con.Close();