用C#写的一个简单的登录及注册的小程序
1,首先设计登录界面,共有三个,如下:
上图登录及注册为linklabel控件,其他为label控件;
上图为登陆界面,两个textbox文本输入框,注册为linklabel控件;
界面设计很简单,不说了。
2,代码介绍:
1)主界面(Form1):
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Hide();
Form3 f3 = new Form3();
f3.ShowDialog();
}//显示注册界面;
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Hide();
Form2 f = new Form2();
f.ShowDialog();
if (f.DialogResult == DialogResult.OK)
{
this.Visible = true;
}
}//显示登录界面;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses();
foreach (System.Diagnostics.Process myProcess in myProcesses)
{
if ("" == myProcess.ProcessName)
myProcess.Kill();
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}//关掉程序;
2)注册界面(Form3)
本文使用的数据库是sql sever2005,先在引用里加入:
using System.Data.SqlClient;
以下为程序代码:
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
bool flagRegister;//定义标志位,确认用户注册
string strConnect = "Data Source=CAI-PC\\SQLEXPRESS;Initial Catalog=MyData1;Persist Security Info=True;User ID=sa;Password=******"; //连接数据库字符串
private void button1_Click(object sender, EventArgs e)
{
if ((textBox1.Text.Length >= 4) && (textBox1.Text.Length <= 12) && (textBox2.Text.Length >= 6) && (textBox3.Text.Length >= 6))
{
flagRegister = true;
}
字符串函数注册登录else
{
if ((textBox1.Text.Length < 4) || (textBox1.Text.Length > 12))
{
MessageBox.Show("用户名长度不在约定范围内,请重新输入!", "提示");
return;
}
if (textBox2.Text.Length < 6)
{
MessageBox.Show("密码长度不足6位,请重新输入!","提示");
return;
}
if (textBox3.Text.Length < 6)
{
MessageBox.Show("请重新输入邮箱!", "提示");
return;
}
}//判断用户名条件;
if (UserFlag == true)
{
MessageBox.Show("用户已经存在,请重新输入!");
return;
}
if (flagRegister == true) //确认用户注册后,把用户写入数据库
{
SqlConnection conConnection = new SqlConnection(strConnect);
conConnection.Open();
string cmd = "insert into 用户(用户名,密码,email) values ('" + textBox1.Text + "'," + "'" + textBox2.Text + "'," + "'" + textBox3.Text + "') ";
SqlCommand com = new SqlCommand(cmd, conConnection);
com.ExecuteNonQuery();
conConnection.Close();
MessageBox.Show("注册成功!点击确定,返回登录界面。", "提示");
this.Close();
Form1 f1 = new Form1();
f1.label2.Text = "欢迎你," + textBox1.Text;
f1.label1.Visible = false;
f1.label3.Visible = false;
f1.linkLabel1.Visible = false;
f1.linkLabel2.Visible = false;
f1.label2.Visible = true;
f1.Show();
}
}
public bool UserFlag; //定义标志位,来确认用户是否存在
private void textBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection conConnection = new SqlConnection(strConnect);
conConnection.Open();
string cmd = "select 用户名 from 用户";
SqlCommand com = new SqlCommand(cmd, conConnection);
SqlDataReader readerUser = com.ExecuteReader();
while (readerUser.Read())
{
if (textBox1.Text == readerUser["用户名"].ToString().Trim())
{
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论