using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace QLBanHang
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string tenDN = txtuser.Text.Trim();
string matkhau = txtpass.Text.Trim();
try
{
if (tenDN == "")
{
MessageBox.Show("Thiếu tên đăng nhập!", "Chú ý!");
txtuser.Select();
return;
}
if (matkhau == "")
{
MessageBox.Show("Hãy nhập mật khẩu!", "Chú ý!");
txtpass.Select();
return;
}
string select = "SELECT * FROM dangnhap";
SqlDataReader dr = DataConn.ThucHienReader(select);
Boolean kt = false;
if (dr != null)
{
while (dr.Read())
{
if (dr.GetString(0) == tenDN && dr.GetString(1) == matkhau)
{
kt = true;
http://mainForm.DisplayAll(); MessageBox.Show("Đăng nhập thành công!");
this.Close();
}
}
}
dr.Close();
dr.Dispose();
if (kt == false)
MessageBox.Show("Bạn nhập sai tên đăng nhập hoặc mật khẩu!");
}
catch
{
MessageBox.Show("loi csdl me roi!");
}
}
}
class DataConn
{
private static string source;
private static SqlConnection con;
private static SqlCommand cmd;
private static SqlDataAdapter da;
private static DataSet ds;
static DataConn()
{
source = "server=(local);uid=sa;database=qlbh;pwd=sa";
con = new SqlConnection(source);
try
{
con.Open();
}
catch (SqlException)
{
MessageBox.Show("Lỗi cơ sở dữ liệu!");
}
}
public static void DongKetNoi()
{
cmd.Dispose();
try
{
con.Close();
}
catch (SqlException)
{
MessageBox.Show("Lỗi cơ sở dữ liệu!");
}
finally
{
con.Dispose();
}
}
public static void ThucHienCmd(string select)
{
cmd = new SqlCommand(select, con);
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException se)
{
MessageBox.Show("Lỗi cơ sở dữ liệu");
MessageBox.Show("" + se.Message);
}
}
public static DataSet GrdSource(string select)
{
da = new SqlDataAdapter(select, con);
ds = new DataSet();
da.Fill(ds);
return ds;
}
public static SqlDataReader ThucHienReader(string select)
{
cmd = new SqlCommand(select, con);
try
{
return cmd.ExecuteReader();
}
catch (SqlException)
{
return null;
}
}
}
}
Chú ý Bạn phải thiết lập CSDL trước phần này đã học ở học kỳ trước
cập nhật tên Server của SQL của máy mình cũng như login và pass... tên CSDL (trong phần Code của mình) nếu không sẽ kết nối dc
Ở C#
Bạn làm như sau
Data - > Add New Datasourse.. -> Chọn Database ( Nhấn Next) - > New Connection -> Chọn Microsoft SQL server -> Continue -> Server Name(tên sqlserver name của bạn) . Chọn Attach a database file :, Chọn file từ button browse - > OK