How to Create Login Form with Access Database in C#
By FoxLearn 10/11/2024 3:35:30 AM 16.48K
Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "AppLogin" and then click OK
Drag and drop the Label, Button, Panel, TextBox controls from your Visual Toolbox onto your form designer, then you can design your login form as shown below.
Open Microsoft Access and create a new database, then create a table named Users
with the following columns:
Username
(Short Text, Primary Key)Password
(Short Text)
You can add a few records for testing.
Open your DataSource, then select 'Add New DataSource' =>Select Microsoft Access DataSource File =>Select your ms access file => Select your datatable
You can also right-click on your project in Solution Explorer, and select Add > New Item.
Choose DataSet
and name it (e.g., UserDataSet.xsd
).
In the Dataset Designer, drag and drop your Users
table from the Server Explorer into the DataSet.
In your project, go to the App.config
file (or create one if it doesn't exist).
Add the connection string for your MS Access database:
<configuration> <connectionStrings> <add name="AccessDbConnection" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=YourDatabase.accdb;" providerName="System.Data.OleDb"/> </connectionStrings> </configuration>
Replace YourDatabase.accdb
with the actual path to your Access database.
Open your form’s code-behind file and write the login logic.
using System; using System.Windows.Forms; namespace AppLogin { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void txtUsername_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)13) 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 { //Get data from user table AppDataTableAdapters.UsersTableAdapter user = new AppDataTableAdapters.UsersTableAdapter(); AppData.UsersDataTable dt = user.GetDataByUsernamePassword(txtUsername.Text, txtPassword.Text); //Check row > 0 if (dt.Rows.Count > 0) { MessageBox.Show("You have been successfully logged in.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); //Process your 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); } } } }
This guide gives you a basic login form using C# and an Microsoft Access database.
VIDEO TUTORIAL