Login form C Sharp.Net

 

C-SharpNET

After Mentioning How you can develop a login form in VB.Net and  login form in VB6 here I will describe the development of login form in C Sharp Dot Net.

Developing a window based login form in C Sharp .Net is a little different from what we have done for VB.Net and Vb6,Here you do not have built in login form so you have to design a simple login form with two text boxes, labels and command buttons.Following screen shot will show you a simple layout

 

 

Login Form

 

 

Specifying Connection String:

In order to use “SqlClient” you have to use System.Data.SqlClient namespace following code will show you how to do it.

using System.Data.SqlClient;

 

Now you can use SqlClient for connection,dataset e.t.c what ever you like. Double click OK button and write following code:

SqlConnection sconn = new SqlConnection("User ID=Username;Password=Password;Initial Catalog=DB Name;Data Source=ServerName/IP");

 

            Form1 formOne = new Form1();

 

            Successful SuccessForm = new Successful();

 

            sconn.Open();

 

            DataSet ds = new DataSet();

 

            SqlDataAdapter da = new SqlDataAdapter("select * from users where username ='" + TxtUsr.Text + "' and password='" + TxtPwd.Text + "'", sconn);

 

            da.Fill(ds);

 

            int count = ds.Tables[0].Rows.Count;

 

              if(count==0)

 

            {

 

                MessageBox.Show("Invalid UserID/Password");

 

            }

 

            else

 

            {

 

                this.Visible = false;

 

                SuccessForm.Visible = true;

 

            }

 

            sconn.Close();

 

The above code will first connect to the SQL Server 2000 database and then object of two forms “Form1″ and “Successful” as “formOne” and “SuccessForm” are initialized then all the operation with the database in order to validate the supplied “username” and “password” if the supplied username and password is correct then “SuccessForm” will be displayed otherwise following message box will be displayed:

 

 

Error Message

 

 

In order to close this form double cancel button and write following code:

this.Close();

 

Hope you have enjoyed this tutorial do not forget to give your feed back.

Tagged: , , , ,
  • soghra

    Thanks.It was very useful.

    • Syed Asad Ahmed

      My Pleasure.Keep visiting for more useful stuff :)

  • Cutie

    Good Staff. Thank you somuch, code works!

    • http://codereflex.net Syed Asad Ahmed

      Thanks for the appreciation :). Keep visiting for more stuff

  • Bryan Gener

    Thank you very much mr. Syed Asad Ahmed. This tutorial is really helpful. Is it ok for you to answer my problems if i’m stuck up in C#. I’m new to this language and i’m willing to learn more. Thank you.

    • http://codereflex.net Syed Asad Ahmed

      Bryan Gener: No Problem :) do ask question if you want, I’ll try my best help you in resolving your problem. Cheers! Enjoy Programming

  • http://yourasif.webs.com Asif Hussain

    I appreciate Mr Sayed Asad Ahmed who don a grate job.

    Nice

    • http://codereflex.net Syed Asad Ahmed

      Thanks Asif and keep visiting :D

  • heiz

    nice post Mr Sayed Asad Ahmed! keep up ur goods post! cheers~~

    • http://codereflex.net Syed Asad Ahmed

      Thanks for the appreciation Heiz and keep visiting for more good post :)

  • javier

    error with sqlException ???

    • http://codereflex.net Syed Asad Ahmed

      Please describe the error in detail.

  • sean

    Hey Syed, that’s great work. But I don’t understand how

    “int count = ds.Tables[0].Rows.Count;

    if(count==0)”

    works!?

    I always get “Invalid UserID/Password” Messagebox, even if its right!

    used 2008 mssql database, varchar types!

    thx alot

    • http://codereflex.net Syed Asad Ahmed

      Sean:

      let me check this i will get back to you very soon.

    • http://codereflex.net Syed Asad Ahmed

      Sean:
      I have checked this on sql server 2008 and it is working fine. what version of visual studio are you using?

      • sean

        I’m glad you answered!

        it’s visual studio 2010 express.

        • http://codereflex.net Syed Asad Ahmed

          let me check this on visual studio 2010

      • http://www.facebook.com/mithun.jana1 Mithun Jana

        Hey sean,

        code is perfect and working fine (in visual studio 2010 express)

  • sean

    mate, you are awesome!

    • http://codereflex.net Syed Asad Ahmed

      Hey Sean:

      It is working fine on VS 2010 as well ! can you send me your code or recheck the userid and password fields.

      • sean

        hey Syed,

        here is the code:

        I didn’t used “con.open();” because “da.Fill” open & close the connection on its own.

        But I also tried with connection open and close; same effect.

        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.Data;
        using System.Text;
        using System.Windows.Forms;
        using System.Data.SqlClient;

        namespace SQLtest
        {
        public partial class Login : Form
        {

        public Login()
        {
        InitializeComponent();
        }

        private void cmdSend_Click(object sender, EventArgs e)
        {

        SqlConnection con = new SqlConnection("Data Source=.\\SQLExpress;" +
        "Initial Catalog=ChatDB;" +
        "User ID=sa;" +
        "Pwd=sa123");

        Login LoginForm = new Login();

        Chat ChatChannel = new Chat();

        DataSet ds = new DataSet();

        SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Loginfiles WHERE user ='" + txtNick.Text + "' and password='" + txtPwd.Text + "'", con);

        da.Fill(ds);

        int count = ds.Tables[0].Rows.Count;

        if (count == 0)
        {

        MessageBox.Show("Invalid UserID/Password");

        }

        else
        {

        this.Visible = false;
        chatchannel.Show();

        }

        }
        }
        }
        <

        • http://codereflex.net Syed Asad Ahmed

          Hey Sean:

          Your code is perfect :-). Check your database values.

          • sean

            it’s working!
            it was sqlservers fault but espacially mine!
            I forgot about the indices! ;)

          • http://codereflex.net Syed Asad Ahmed

            Ok That’s Great! The problem was identified and Resolved !! All’s well that ends well

            Enjoy Programming.

  • Kestas

    Thank you for the code, it works almost perfectly, exept when I try to login on the first time after registration(code, I have made myself) I get an error by debugger. It says “Cannot open database “db” requested by the login. The login failed.
    Login failed for user ‘PC’.” After this crash, when I start the debugger again, it works with the same username and password fine. Any ideas?
    Thank you.

    • http://codereflex.net Syed Asad Ahmed

      Hey Kestas:
      Can you send me your code?

  • Alexandru

    SqlDataAdapter da = new SqlDataAdapter(“SELECT * FROM Loginfiles WHERE user =’” + txtNick.Text + “‘ and password=’” + txtPwd.Text + “‘”, con);

    You should have used SQLCommand and SqlParameter to pass the username and password. Your code is vunerable to SQL injection.

    Correct:

    SqlCommand cmd = new SqlCommand("SELECT * FROM Loginfiles WHERE user = @username and password=@password"", conn);

    SqlParameter ParamUsername = new SqlParameter("@username", SqlDbType.VarChar);

    cmd.Parameters.Add(ParamUsername);
    ParamUsername.Value = txtNick.Text;

    SqlParameter ParamPassword = new SqlParameter("@parola", SqlDbType.VarChar);
    cmd.Parameters.Add(ParamPassword);
    ParamPassword.Value = txtPwd.Text;

    int found = Convert.ToInt32(cmd.ExecuteScalar());
    if (found <= 0)
    {
    MessageBox.Show("Incorrect username or password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    return;
    }
    else
    {
    //success
    }

    • Alexandru

      Replace @parola with @password.

      • http://codereflex.net Syed Asad Ahmed

        Okay! Thanks for the correction. I would definitely use this practice from now on in my tutorials.

        Appreciate your concern towards my post.

    • karthik

      thak uuu very useful 11111111111……

  • Alexandru

    Your password shouldn’t be saved in clear text in the database.

    public sealed class Crypter
    {
    public static string MD5Hash(string text)
    {
    MD5 md5 = new MD5CryptoServiceProvider();
    byte[] data = Encoding.Default.GetBytes(text);
    byte[] hash = md5.ComputeHash(data);
    string hexaHash = "";
    foreach (byte b in hash)
    {
    hexaHash += String.Format("{0:x2}", b);
    }
    return hexaHash;
    }

    }

    Replace

    cmd.Parameters.Add(paramparola);
    paramparola.Value = Crypter.MD5Hash(parolatextBox.Text);

  • niraj

    Thanks buddy i m searching form long time

    • http://codereflex.net Syed Asad Ahmed

      My pleasure Niraj

  • http://www.facebook.com/profile.php?id=100002134627653 Nitin Biltoria

    thnks dear, its very helpful!!!!!!!!!!!!1

  • Raju Rai

    thank for that , these code fully succesful

  • Raghavmsv

    hi there,      
     i’ve tried the code it works fine but iam getting invalid username/password, which is after creating my table…
    plzzz help any one
                                           raghav

    • http://codereflex.net Syed Asad Ahmed

      Can you explain it in a more detail at the database level. I mean database values.

  • Sgiri580

    nive code yaar
     

  • Aswathyjayakumar14

    thankkkksss nice………

  • sonali

    code is little bit understandable

  • Selva Kumar397

    Thanks. This code very useful for .net developer ,code are very simple and understandable

  • Kpriya1189

    is der any code for advance login page creation

  • Kpriya

    is der any advance login page creation coding.can u help me?

    • SyedAsadAhmed

      What do you mean by advance login page

  • naresh

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Windows.Forms;

    using System.Data.SqlClient;

    namespace unpwd

    {

    public partial class Form1 : Form

    {

    public Form1()

    {

    InitializeComponent();

    }

    SqlConnection con = new SqlConnection(@”Server=ADMIN-974CC165BSQLEXPRESS;Database=naresh;Integrated Security=True”);

    private void button1_Click(object sender, EventArgs e)

    {

    SqlCommand cmd = new SqlCommand(“select USERNAME,PASSWORD from login”, con);

    con.Open();

    SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

    //Make sure that the data is ppresent

    if (dr.HasRows)

    {

    while (dr.Read())

    {

    // Make sure that the user is exists

    if (textBox1.Text == dr.GetValue(0).ToString())

    {

    if (textBox2.Text == dr.GetValue(1).ToString())

    {

    // Check the password of the user

    MessageBox.Show(“User Enteres”);

    Form f = new Form();

    f.Show();

    }

    else

    MessageBox.Show(“Invalid user”);

    }

    //else

    //MessageBox.Show(“Invalid user”);

    }

    }

    con.Close();

    }

    }

    }

    • vaibhav kumar

      I’m xctly searching for the same..Thank you..

  • it jobs in hyderabad

    i found this very informative thanks a lot for

    sharing

GetSocial