public partial class FormSignup : Form
{
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\USER\source\repos\ProjectV2\ProjectV2\Account.mdf;Integrated Security=True");
    SqlCommand cmd;
    int ID = 0;
    public FormSignup()
    {
        InitializeComponent();
    }
    private void btnSignup_Click(object sender, EventArgs e)
    {
        con.Open();
        cmd = new SqlCommand("select * from Account where Name='" + txtName.Text + "' and Password ='" + txtPassword.Text + "'", con);
        SqlDataReader rd = cmd.ExecuteReader();
        if (rd.HasRows)
        {
            MessageBox.Show("A account with this Name has been registered. Please try select another username.");
            con.Close();
            ClearData();
            return;
        }
        if (txtPassword.Text != txtRetypePassword.Text)
        {
            MessageBox.Show("Please re-enter password.");
            con.Close();
            ClearData();
            return;
        }
        if (txtName.Text != "" && txtPassword.Text != "" && txtContactNumber.Text != "" && txtAddress.Text != "")
        {
            cmd = new SqlCommand("insert into Account(Name,Password,ContactNumber,Address) values(@name,@password,@contactnumber,@address)", con);
            con.Open();
            cmd.Parameters.AddWithValue("@name", txtName.Text);
            cmd.Parameters.AddWithValue("@password", txtPassword.Text);
            cmd.Parameters.AddWithValue("@contactnumber", txtContactNumber.Text);
            cmd.Parameters.AddWithValue("@address", txtAddress.Text);
            con.Close();
            cmd.ExecuteNonQuery();
            MessageBox.Show("Record Inserted Successfully");
            ClearData();
        }
        else
        {
            MessageBox.Show("Please Provide All Deatails!");
        }
    }
            Asked
            
        
        
            Active
            
        
            Viewed 35 times
        
    -2
            
            
         
    
    
        halfer
        
- 19,824
- 17
- 99
- 186
 
    
    
        Elaina Niki
        
- 3
- 1
- 
                    Not all paths in `btnSignup_Click` close the connection, so next time it will be still opened when you try to open it. You have more serious issues with your code though, please have a look at https://stackoverflow.com/q/332365/11683 and https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement. – GSerg Jun 04 '20 at 09:56
1 Answers
0
            Try this:
private void btnSignup_Click(object sender, EventArgs e)
    {
        using (con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\USER\source\repos\ProjectV2\ProjectV2\Account.mdf;Integrated Security=True")
        {
          con.Open();
          ...
        }
    }
 
    
    
        Leszek Mazur
        
- 2,443
- 1
- 14
- 28