Wednesday, March 9, 2016

Membuat Form Login Dengan C# Dan Database Access

1. Berikut design form login yang sudah saya buat





2. Buat tabel usersetup seperti di bawah ini

  



3. Berikut View Codenya

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.OleDb;

namespace MyResto
{
    public partial class FrmLogin : Form
    {

        MainMenu menu = new MainMenu();

        public FrmLogin()
        {
            InitializeComponent();
        }

       

        private void btnlogin_Click(object sender, EventArgs e)
        {
            LoginUser();
        }


        private void LoginUser() {
                try
                {
                    string sql;
                    OleDbCommand cmd;
                    OleDbDataAdapter da;

                    DataSet ds = new DataSet("ds");

                    OleDbConnection connection = new OleDbConnection();
                    connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + Application.StartupPath + "/data.mdb";

                    connection.Open();

                    sql="select * from usersetup where userid = '" + txtuser.Text + "'";
                    cmd = new OleDbCommand(sql, connection);
                    da = new OleDbDataAdapter(cmd);

                    da.Fill(ds);

                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        if (txtpassword.Text.ToLower().Trim() == ds.Tables[0].Rows[0]["password"].ToString().Trim().ToLower())
                        {
                            this.Hide();
                            txtpassword.Text = "";
                            menu.Show();
                        }
                        else
                        {
                            MessageBox.Show("Password salah");
                            txtpassword.Focus();
                        }
                    }
                    else {
                        MessageBox.Show("User id tidak terdaftar");
                        txtuser.Focus();
                    }

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

        private void btnexit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void txtuser_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) {
                btnlogin_Click(sender, e);
            }
          
        }



        private void txtpassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnlogin_Click(sender, e);
            }

        }


    }
}

3 comments: