Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Windows GimmeCode
I need creat login form. Design is ok.But i hvnt code.Pls gime code for loging form in c#
Posted 18-Dec-11 19:42pm
Edited 20-Dec-11 0:53am
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

It's a basic thing. You have design form then why not code it ?
Every control has events. if you design the forms means you know the logic behind it.
just go ahead. here are some steps that will help you.
 
1. Validate empty Username and password textbox.
2. Make SQL connection and Fetch password with the help of username
3. if no record fetch alert user "Userid not exist"
4. if record exist check against entered password, if mismatched, alert user "Wrong password"
 
Here is example,Login with example C#.net[^]
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;
    using System.Windows.Forms;
     
    namespace daniweb
    {
    public partial class frmLogin : Form
    {
    /// <summary>
    /// Key for the crypto provider
    /// </summary>
    private static readonly byte[] _key = { 0xA1, 0xF1, 0xA6, 0xBB, 0xA2, 0x5A, 0x37, 0x6F, 0x81, 0x2E, 0x17, 0x41, 0x72, 0x2C, 0x43, 0x27 };
    /// <summary>
    /// Initialization vector for the crypto provider
    /// </summary>
    private static readonly byte[] _initVector = { 0xE1, 0xF1, 0xA6, 0xBB, 0xA9, 0x5B, 0x31, 0x2F, 0x81, 0x2E, 0x17, 0x4C, 0xA2, 0x81, 0x53, 0x61 };
     
    public frmLogin()
    {
    InitializeComponent();
    }
     
     
    #if (DEBUG) //Only compile this method for local debugging.
    /// <summary>
    /// Decrypt a string
    /// </summary>
    /// <param name="Value"></param>
    /// <returns></returns>
    private static string Decrypt(string Value)
    {
    SymmetricAlgorithm mCSP;
    ICryptoTransform ct = null;
    MemoryStream ms = null;
    CryptoStream cs = null;
    byte[] byt;
    byte[] _result;
     
    mCSP = new RijndaelManaged();
     
    try
    {
    mCSP.Key = _key;
    mCSP.IV = _initVector;
    ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
     
     
    byt = Convert.FromBase64String(Value);
     
    ms = new MemoryStream();
    cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
    cs.Write(byt, 0, byt.Length);
    cs.FlushFinalBlock();
     
    cs.Close();
    _result = ms.ToArray();
    }
    catch
    {
    _result = null;
    }
    finally
    {
    if (ct != null)
    ct.Dispose();
    if (ms != null)
    ms.Dispose();
    if (cs != null)
    cs.Dispose();
    }
     
    return ASCIIEncoding.UTF8.GetString(_result);
    }
    #endif
     
    /// <summary>
    /// Encrypt a string
    /// </summary>
    /// <param name="Password"></param>
    /// <returns></returns>
    private static string Encrypt(string Password)
    {
    if (string.IsNullOrEmpty(Password))
    return string.Empty;
     
    byte[] Value = Encoding.UTF8.GetBytes(Password);
    SymmetricAlgorithm mCSP = new RijndaelManaged();
    mCSP.Key = _key;
    mCSP.IV = _initVector;
    using (ICryptoTransform ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV))
    {
    using (MemoryStream ms = new MemoryStream())
    {
    using (CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write))
    {
    cs.Write(Value, 0, Value.Length);
    cs.FlushFinalBlock();
    cs.Close();
    return Convert.ToBase64String(ms.ToArray());
    }
    }
    }
    }
     
    /// <summary>
    /// Looks up the users password crypto string in the database
    /// </summary>
    /// <param name="Username"></param>
    /// <returns></returns>
    private static DataTable LookupUser(string Username)
    {
    /*
      * The reason I return a datatable here is so you can also bring back the user's full
      * name, email address, security rights in the application, etc. I have a "User" class
      * where I defined meta information for users.
      */
    const string connStr = "Data Source=apex2006sql;Initial Catalog=Leather;Integrated Security=True;";
    const string query = "Select Password From UserTable (NOLOCK) Where UserName = @UserName";
    DataTable result = new DataTable();
    using (SqlConnection conn = new SqlConnection(connStr))
    {
    conn.Open();
    using (SqlCommand cmd = new SqlCommand(query, conn))
    {
    cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = Username;
    using (SqlDataReader dr = cmd.ExecuteReader())
    {
    result.Load(dr);
    }
    }
    }
    return result;
    }
     
    /// <summary>
    /// Obviously the .Focus() code doesn't apply to ASP.NET
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void buttonLogin_Click(object sender, EventArgs e)
    {
    if (string.IsNullOrEmpty(textBoxUsername.Text))
    {
    //Focus box before showing a message
    textBoxUsername.Focus();
    MessageBox.Show("Enter your username", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
    //Focus again afterwards, sometimes people double click message boxes and select another control accidentally
    textBoxUsername.Focus();
    return;
    }
    else if (string.IsNullOrEmpty(textBoxPassword.Text))
    {
    textBoxPassword.Focus();
    MessageBox.Show("Enter your password", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
    textBoxPassword.Focus();
    return;
    }
     
    //OK they enter a user and pass, lets see if they can authenticate
    using (DataTable dt = LookupUser(textBoxUsername.Text))
    {
    if (dt.Rows.Count == 0)
    {
    textBoxUsername.Focus();
    MessageBox.Show("Invalid username.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
    textBoxUsername.Focus();
    return;
    }
    else
    {
    //Always compare the resulting crypto string or hash value, never the decrypted value
    //By doing that you never make a call to Decrypt() and the application is harder to
    //reverse engineer. I included the Decrypt() method here for informational purposes
    //only. I do not recommend shipping an assembly with Decrypt() methods.
     
    string dbPassword = Convert.ToString(dt.Rows[0]["Password"]);
    string appPassword = Encrypt(textBoxPassword.Text); //we store the password as encrypted in the DB
    if (string.Compare(dbPassword, appPassword) == 0)
    {
    //Logged in
    }
    else
    {
    //You may want to use the same error message so they can't tell which field they got wrong
    textBoxPassword.Focus();
    MessageBox.Show("Invalid Password", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
    textBoxPassword.Focus();
    return;
    }
    }
    }
    }
    }
    }
  Permalink  
v3
Comments
RaviRanjankr at 20-Dec-11 5:44am
   
[Edited]code is wrapped in pre tag[/Edited]
RaviRanjankr at 20-Dec-11 5:45am
   
Only code is not enough. you should elaborate it.
palanivelloganathan at 2-Apr-13 6:19am
   
i create a login form program .,its dont have any error but its not run . i know the problem have in sql connection will you pls tell some solution for my pronlem. here i attach that.
 
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 WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
 
private void button1_Click(object sender, EventArgs e)
{
string userid, password;
userid = textBox1.Text;
password = textBox2.Text;
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Login;User ID=sa;Password=gs123");
con.Open();
SqlCommand cmd = new SqlCommand("select username,password from admin where username='" + textBox1.Text + "' and password='" + textBox2.Text + " '", con);
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();

while (dr.Read())
{
if (textBox1.Text == dr[0].ToString() && textBox2.Text == dr[1].ToString())
{
textBox1.Text = "";
textBox2.Text = "";
this.Hide();

}
else
{
MessageBox.Show("invalid userid or password");
}
dr.Close();
con.Close();
}
}
 
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
kiranraavi2 at 12-Nov-13 13:30pm
   
Try after commenting "cmd.ExecuteNonQuery();"
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

private void CmbtnLogin_Click(object sender, EventArgs e)
        {
           
            try
            {
                if (string.IsNullOrEmpty(this.txtUn.Text))
                {
                    MessageBox.Show("Enter User Name","Enter User Name");
                    txtUn.Focus();
                }
                else if (string.IsNullOrEmpty(this.txtPw.Text))
                {
                    MessageBox.Show("Enter Password","Enter Passwrod");
                    txtPw.Focus();
                }
                else if (CboUnits.SelectedIndex <= -1)
                {
                    MessageBox.Show("Select Unit","Select Unit");
                    CboUnits.Focus();
                }
                else if (string.IsNullOrEmpty(this.txtUn.Text) | string.IsNullOrEmpty(this.txtPw.Text) | string.IsNullOrEmpty(CboUnits.Text))
                {
                    MessageBox.Show("Provide User Name and Password");
                }
                else
                {
                   
                    sq = "Select UN,PW,Units from Login";
                    Cmd = new System.Data.SqlClient.SqlCommand(sq,Con);
                    Dr = Cmd.ExecuteReader();
                    if (Dr.Read())
                    {
                        string Uname = txtUn.Text;
                        string PWord = txtPw.Text;
                        string type = CboUnits.Text;
 
                        if (Dr["UN"].ToString() == Uname && Dr["PW"].ToString() == PWord && Dr["Units"].ToString()==type )
                        {
                            /*frmFind fnd = new frmFind();
                            fnd.Show();*/
                            MDIParent1 mdi = new MDIParent1();
                            mdi.Show();
                            frmRawmat INV = new frmRawmat();
                            
                            
                        }
 
                        else
                       
                        {
                            if (Dr["UN"].ToString() != Uname)
                            {
                                MessageBox.Show("Invalid User Name","Invalid User Name");
                                txtUn.Clear();
                                txtUn.Focus();
                            }
                            else if (Dr["PW"].ToString() != PWord)
                            {
                                MessageBox.Show("Invalid Password","Invalid Password");
                                txtPw.Clear();
                                txtPw.Focus();
                             }
                             else if (Dr["Units"].ToString() != type)
                             {
                                 MessageBox.Show("invalid Unit","Invalid Unit");
                                 CboUnits.SelectedIndex = -1;
                                 CboUnits.Text = ("[Select]");
                                 CboUnits.Focus();
                             }
 
                            }
                         }
                    
                    Dr.Close();
                    Cmd.Dispose();
                          }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
                         
        }
  Permalink  
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 200
1 Kamal Rocks 184
2 PIEBALDconsult 150
3 BillWoodruff 148
4 Jochen Arndt 135
0 OriginalGriff 5,695
1 DamithSL 4,506
2 Maciej Los 4,007
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,190


Advertise | Privacy | Mobile
Web04 | 2.8.141216.1 | Last Updated 24 May 2014
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100