Login Code

  • 1.8K Views
  • Last Post 29 March 2018
Abdulkhaliq posted this 21 March 2018

like login button

sql server Tbl for login form

admin posted this 29 March 2018

First i think you need to create a new database, then run the sql script as below to create a user table

CREATE TABLE [dbo].[Users](
    [UserName] [varchar](25) NOT NULL,
    [Password] [varchar](50) NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
    [UserName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Now, create a new windows forms project, then design your login form as below, you can design a beautiful login form

c# login form

OK, that's time we use entity framework to check login

Right click on your project, then select Add New Item

entity framework

Select ADO.Net Entity Data Model and put your name is Model

c# entity framework

The next screen we select EF Designer from database

entity framework c#

You need to enter account information to connect to your sql database

c# entity framework login

Select include the connectionstring in app.config file, then enter with name is DbEntites

c# login form

The next screen you can select the version entity framework that you want to use, then click next button

c# login form

Select User table, then enter your model namespace is DbModel and click Finish

c# entity framework 6

Now, Open your login form and double click on the login button to add event handle code to login form

private void btnLogin_Click(object sender, EventArgs e)
{
    using (DbEntities db = new DbEntities())
    {
        var query = from u in db.Users
                    where u.UserName == txtUserName.Text && u.Password == txtPassword.Text
                    select u;
        if (query.SingleOrDefault() != null)
            MessageBox.Show("Login succesfull !");
        else
            MessageBox.Show("Login fail !");
    }
}

You can use LinQ to check user login. Now, Open your user table then insert some data to play demo

Close