Best Way to Create Login Form using C# and Mysql database






If we look at above screen shot
We have the following
User Type
UserName
Password
Note that all the three elements were created using labels and remember each label you create you need a text box that will capture data from the users.
Note that each textbox will have a name like textbox for user type its name is at, Textbox UserName its name is un and text box Password its name is pw.
After doing that Double click your button login to go to the coding window , copy and paste the following codes.
try
{
string myConnection = "datasource=localhost;port=3306;username=root;";
MySqlConnection mycon = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand("Select * from   hwms.login where UserName= '" + this.un.Text + "' and PassWord ='" + this.pw.Text + "'and UserType='" + this.at.Text + "';", mycon);
 MySqlDataReader myReader;
 mycon.Open();
 myReader = SelectCommand.ExecuteReader();
 int count = 0;
 while (myReader.Read())
 {
 count = count + 1;
  }

   if (count == 1)
   {
  MessageBox.Show("UserName and PassWord correct and granted access");
  if (at.Text == "Administrator")
  {
 Main y = new Main();
  y.Show();
  this.Visible = false;
   }

if (at.Text == "User")
 {
 Main X = new Main();
  X.Show();
  this.Visible = false;
                        // this will make following component not to appear if i log in as a user
                        //X.userRegistrationToolStripMenuItem.Enabled = false;
                        //X.generalRegistrationToolStripMenuItem.Enabled = false;
                        //X.healthWorkerAllocationToolStripMenuItem.Enabled = false;
                        //X.atendanceToolStripMenuItem.Enabled = false;
}
}
else if (count > 1)
{
                    // here am checking in the database to see whether there is any entry fielled and if yes it will return the message below
MessageBox.Show("Duplicate user in the database and access denied", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
// here am clearing all the filleds 
pw.Text = "";
 un.Text = "";
 at.Text = "";
 }
 else
 MessageBox.Show("username and password combination does not macth", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
 // the code below clears thusername and password if they are not correct.
  pw.Text = "";
  un.Text = "";
 at.Text = "";
  //it ends here
    mycon.Close();
    }
  catch (Exception ex)
   {
   MessageBox.Show(ex.Message);
   }
  Note: After you have inserted in the codes in the coding window of the login  button we need to add

using MySql.Data.MySqlClient; at the top of our code to recall the lib "MySql.Data.dll"

Note3 hwms is the database name . login is the table name
I think at that level you are done. Thanks for visiting www.luckycoders.com please give you opnion about the code. 
 

Related Posts
Previous
« Prev Post

Contact Form

Name

Email *

Message *