To create a login form in C# that connects to a database, you will need to use a combination of C# code and SQL commands. Here are the general steps to create a login form that connects to a database:
- Create a new C# Windows Forms project.
- Design the form by adding textboxes for the username and password, and a button to submit the login information.
- Add a reference to the ADO.NET data provider for the database you are using (e.g. MySQL, SQL Server, etc.)
- Use ADO.NET to connect to the database and execute a SQL command to check if the entered username and password match any records in the database.
- If a match is found, allow the user to proceed. If no match is found, display an error message.
You can also use ORM(Object-relational mapping) libraries like Entity Framework to connect to the database and perform CRUD operations.
It’s recommended that you use a parameterized query and hash the password before storing in the database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | using System; using System.Data; using MySql.Data.MySqlClient; using System.Windows.Forms; namespace LoginForm { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnLogin_Click(object sender, EventArgs e) { string connString = "Server=localhost;Database=mydb;Uid=root;Pwd=password;"; using (MySqlConnection conn = new MySqlConnection(connString)) { conn.Open(); string sql = "SELECT COUNT(*) FROM users WHERE username=@username AND password=@password"; MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.Parameters.AddWithValue("@username", txtUsername.Text); cmd.Parameters.AddWithValue("@password", txtPassword.Text); int count = Convert.ToInt32(cmd.ExecuteScalar()); if (count == 1) { MessageBox.Show("Successful login"); } else { MessageBox.Show("Invalid username or password"); } } } } } |