Search code examples
c#winformsconnection-stringsqlexceptionsystem.data.sqlclient

Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll In VS2019


Im a beginner, and new to C#, i don't know how to fix this bug, please help SQL Service is running, VS2019 is updated to newest and i am Windows 11. It only said Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll Code:

string cs = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\LoginDB.mdf;Integrated Security=True;";
            private void Loginbutton_Click(object sender, EventArgs e)
            {
                if (LoginTextBox.Text == "" || PassTextBox.Text == "") // Nếu 1 trong 2 ô trống thì
                {
                    MessageBox.Show("Missing login name or password");
                    return;
                }
                try
                {
                    SqlConnection con = new SqlConnection(cs);
                    SqlCommand cmd = new SqlCommand("Select * from LoginDB where UserName=@username and Password=@password", con);
                    cmd.Parameters.AddWithValue("@username", LoginTextBox.Text);
                    cmd.Parameters.AddWithValue("@password", PassTextBox.Text);
                    con.Open();
                    SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    adapt.Fill(ds);
                    con.Close();
                    int count = ds.Tables[0].Rows.Count;
                    //If count =1 thì hiện f2(Menu)
                    if (count == 1)
                    {
                        MessageBox.Show("Login Successfully!");
                        this.Visible = false;
                        Menu f2 = new Menu();
                        f2.Show();
                    }
                    else
                    {
                        MessageBox.Show("Login Name or password is wrong");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            } 

Solution

  • SQL is just too hard for me, may be i will go .xlsx, yes i know its very inseccure but I quit, thanks anyway