Windows Forms: Create Login Form with SQL Server in C#
By FoxLearn 6/4/2017 10:35:24 AM 10.89K
How to Create a Login Window with SQL Server in C#
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "LoginForm" and then click OK
Step 2: Design your login form as below
Step 3: Create a user table, then add the user table to Entity Framework Model First as below
Step 4: Add a click event handler to the button
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LoginForm { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void txtUsername_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)13)//Enter key txtPassword.Focus(); } private void txtPassword_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)13) btnLogin.PerformClick(); } private void btnLogin_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtUsername.Text)) { MessageBox.Show("Please enter your username.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning); txtUsername.Focus(); return; } try { using (TestEntities test = new TestEntities()) { //using linq to query data var query = from o in test.Users where o.Username == txtUsername.Text && o.Password == txtPassword.Text select o; //check if user exists if (query.SingleOrDefault() != null) { MessageBox.Show("You have been successfully logged in.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); //Add your code process login here } else { MessageBox.Show("Your username or password is incorrect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
VIDEO TUTORIALS
Categories
Popular Posts
Visual Studio: Auto increment version
03/22/2024
What is ARM architecture?
03/11/2024