简单实现:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 using System.Data.SqlClient;10 using System.Text.RegularExpressions;11 12 namespace 用户登录13 {14 public partial class Form1 : Form15 {16 public Form1()17 {18 InitializeComponent();19 }20 private void but1_Click(object sender, EventArgs e)21 {22 if (string.IsNullOrWhiteSpace(textb1.Text) ||23 textb2.Text == "" ||24 textb3.Text == "")25 {26 MessageBox.Show("请输入正确的信息");27 return;28 }29 if (textb2.Text.Trim() != textb3.Text.Trim())30 {31 MessageBox.Show("两次密码输入不正确");32 return;33 }34 string uid = textb1.Text.Trim();35 string pwd = textb2.Text.Trim();36 string sqlconn = @"server=.;database=MyDataBase;Integrated security=true";37 string sql = string.Format("insert into UseLogin(name,pwd) values('{0}','{1}');", uid, pwd);38 using (SqlConnection conn = new SqlConnection(sqlconn))39 {40 using (SqlCommand cmd = new SqlCommand(sql, conn))41 {42 if (conn.State == ConnectionState.Closed)43 {44 conn.Open();45 }46 try47 {48 int res = cmd.ExecuteNonQuery();49 textb1.Clear();50 textb2.Text = string.Empty;51 textb3.Text = "";52 MessageBox.Show(string.Format("{0}行受影响", res));53 }54 catch (Exception ex)55 {56 MessageBox.Show(ex.Message);57 }58 }59 }60 }61 private void textb1_Leave(object sender, EventArgs e)62 {63 string sqlconn = @"server=.;database=MyDataBase;Integrated security=true";64 string sql = string.Format(@"select count(*) from uselogin where name='{0}'", textb1.Text.Trim());65 using (SqlConnection conn = new SqlConnection(sqlconn))66 {67 using (SqlCommand cmd = new SqlCommand(sql, conn))68 {69 if (conn.State == ConnectionState.Closed)70 {71 conn.Open();72 }73 int set = Convert.ToInt32(cmd.ExecuteScalar());74 if (Regex.IsMatch(textb1.Text.Trim(), @"^\w{0,10}$"))75 {76 if (set != 0)77 {78 label4.ForeColor = Color.Red;79 label4.Text = "该用户名存在,请重新输入";80 }81 else82 {83 label4.ForeColor = Color.Blue;84 label4.Text = "√";85 }86 }87 else88 {89 label4.ForeColor = Color.Red;90 label4.Text = "该用户长度,请重新输入";91 }92 }93 }94 }95 }96 }