Showing posts with label user name display in c#. Show all posts
Showing posts with label user name display in c#. Show all posts

Saturday, November 26, 2016

Login and Display User Name in C# and Microsoft SQL Server

In this article I revised my previous code with the help of my good friend and fellow software engineer Mr. Alfel Benvic G. Go. Thank you very much Sir Bon for the help you provided to me.  We modify the code that enables the user to login and our program will welcome the user in our application by displaying the message welcome and the name of the user for example the name of the user is John Smith if John Smith successfully login in our system our welcome page will display Welcome John Smith the name John Smith is the record that is being retrieved from our database. I  have seen many questions all over the web asking how to do this functionality in our login page here is the solution very straight forward and easy to understand.  I hope you will find our work useful in learning C# programming. Take note we are using Microsoft Visual Studio 2012 Ultimate Edition and Microsoft SQL Server 2008 R2 as our development tool in this login system.


Add me at Facebook my address is jakerpomperada@gmail.com and jakerpomperada@yahoo.com

My email address are the following jakerpomperada@gmail.com and jakerpomperada@yahoo.com

My mobile number here in the Philippines is 09173084360.









Sample Program Output

Program Listing

Form1.cs

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace login
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private String fname;
        private String lname;


        private void btn_close_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you want to exit?", "Login System",
         MessageBoxButtons.YesNo, MessageBoxIcon.Question)
         == DialogResult.Yes)
            {
                Application.Exit();
            }
            else
            {
                txt_username.Focus();
            }
        }

        private void getTheName(String username)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=access;Integrated Security=true;";
            String query = "SELECT firstname AS a, lastname AS b FROM tbl_access WHERE username = @username";
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.Parameters.AddWithValue("@username", username);
                cmd.ExecuteScalar();
                SqlDataReader rdr = cmd.ExecuteReader();
                if (rdr.Read())
                {
                    fname = rdr["a"].ToString();
                    lname = rdr["b"].ToString();
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                con.Close();
            }
        }

        private void btn_ok_Click(object sender, EventArgs e)
        {
             if(txt_username.Text=="" || txt_password.Text=="")
            {
                MessageBox.Show("Please provide UserName and Password");
                return;
            }
            try
            {
                //Create SqlConnection
                SqlConnection con =  new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=access;Integrated Security=true;");
                SqlCommand cmd = new SqlCommand("Select * from tbl_access where username=@username AND password_1=@password",con);
                cmd.Parameters.AddWithValue("@username",txt_username.Text);
                cmd.Parameters.AddWithValue("@password", txt_password.Text);
                con.Open();
                SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adapt.Fill(ds);
                con.Close();
                int count = ds.Tables[0].Rows.Count;
                string str;

                 str = "select * from tbl_access";
                SqlCommand com = new SqlCommand(str, con);
                con.Open();
                SqlDataReader reader = com.ExecuteReader();


                if (count == 1)
                {
                    MessageBox.Show("Login Successful!");
                    this.getTheName(txt_username.Text);
                    this.Hide();
                    Form2 fm = new Form2();
                    fm.Uname = fname.Trim();
                    fm.Lname = lname.Trim();
                    fm.Show();
                  
                 }
                else
                {
                    MessageBox.Show("Login Failed!!! Try Again.");
                    txt_username.Text = "";
                    txt_password.Text = "";
                    txt_username.Focus();
                }
                
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txt_username_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txt_password.Focus();
            }
        }

        private void txt_password_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (txt_username.Text == "" || txt_password.Text == "")
                {
                    MessageBox.Show("Please provide UserName and Password");
                    return;
                }
                try
                {
                    //Create SqlConnection
                    SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=access;Integrated Security=true;");
                    SqlCommand cmd = new SqlCommand("Select * from tbl_access where username=@username AND password_1=@password", con);
                    cmd.Parameters.AddWithValue("@username", txt_username.Text);
                    cmd.Parameters.AddWithValue("@password", txt_password.Text);
                    con.Open();
                    SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    adapt.Fill(ds);
                    con.Close();
                    int count = ds.Tables[0].Rows.Count;
                    string str;

                    str = "select * from tbl_access";
                    SqlCommand com = new SqlCommand(str, con);
                    con.Open();
                    SqlDataReader reader = com.ExecuteReader();


                    if (count == 1)
                    {
                        MessageBox.Show("Login Successful!");
                        this.getTheName(txt_username.Text);
                        this.Hide();
                        Form2 fm = new Form2();
                        fm.Uname = fname.Trim();
                        fm.Lname = lname.Trim();
                        fm.Show();

                    }
                    else
                    {
                        MessageBox.Show("Login Failed!!! Try Again.");
                        txt_username.Text = "";
                        txt_password.Text = "";
                        txt_username.Focus();
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        }
    }

Form2.cs

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 login
{
    public partial class Form2 : Form
    {
        private String uname;

        public String Uname
        {
            get { return uname; }
            set { uname = value; }
        }

        private String lname;

        public String Lname
        {
            get { return lname; }
            set { lname = value; }
        }

        public Form2()
        {
            InitializeComponent();
        }

        private void btn_logout_Click(object sender, EventArgs e)
        {
            Application.ExitThread();

        }

        private void Form2_Load(object sender, EventArgs e)
        {
            label1.Text = "Welcome " + Uname + " " + Lname;
        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.ExitThread();
        }
    }
}

SQL Dumb File

access.sql

USE [master]
GO
/****** Object:  Database [access]    Script Date: 11/25/2016 20:39:55 ******/
CREATE DATABASE [access] ON  PRIMARY 
( NAME = N'access', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\access.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'access_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\access_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
ALTER DATABASE [access] SET COMPATIBILITY_LEVEL = 100
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [access].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [access] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [access] SET ANSI_NULLS OFF
GO
ALTER DATABASE [access] SET ANSI_PADDING OFF
GO
ALTER DATABASE [access] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [access] SET ARITHABORT OFF
GO
ALTER DATABASE [access] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [access] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [access] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [access] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [access] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [access] SET CURSOR_DEFAULT  GLOBAL
GO
ALTER DATABASE [access] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [access] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [access] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [access] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [access] SET  DISABLE_BROKER
GO
ALTER DATABASE [access] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [access] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [access] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [access] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [access] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [access] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [access] SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [access] SET  READ_WRITE
GO
ALTER DATABASE [access] SET RECOVERY SIMPLE
GO
ALTER DATABASE [access] SET  MULTI_USER
GO
ALTER DATABASE [access] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [access] SET DB_CHAINING OFF
GO
USE [access]
GO
/****** Object:  Table [dbo].[tbl_access]    Script Date: 11/25/2016 20:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_access](
[id] [int] IDENTITY(1,1) NOT NULL,
[username] [nchar](100) NULL,
[password_1] [nchar](100) NULL,
[lastname] [nchar](100) NULL,
[firstname] [nchar](100) NULL
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[tbl_access] ON
INSERT [dbo].[tbl_access] ([id], [username], [password_1], [lastname], [firstname]) VALUES (2, N'allie                                                                                               ', N'iya                                                                                                 ', N'POMPERADA                                                                                           ', N'MA. JUNALLIE                                                                                        ')
INSERT [dbo].[tbl_access] ([id], [username], [password_1], [lastname], [firstname]) VALUES (3, N'iya                                                                                                 ', N'iya                                                                                                 ', N'POMPERADA                                                                                           ', N'JULIANNA RAE                                                                                        ')
INSERT [dbo].[tbl_access] ([id], [username], [password_1], [lastname], [firstname]) VALUES (4, N'jake                                                                                                ', N'123                                                                                                 ', N'POMPERADA                                                                                           ', N'JAKE                                                                                                ')
SET IDENTITY_INSERT [dbo].[tbl_access] OFF