自学C#,练习。登录注册窗体,功能:点击注册将输入的信息储存在sqlserver数据库中,并判断账号是否已被注册过(数据库中是否已有该账号),点击登录若账号密码信息数据库中已存在即登录成功。
另外如果把.EXE程序拷到别的电脑上这个程序还能不能运行
欢迎新手一起学习~望大神指点还有哪些地方需要改进~
界面:
话不多说直接上代码
注册窗体的代码
using System;
using System.Collections.Generic;using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
public partial class Register : Form
{
public Register()
{
InitializeComponent();
}
//清空输入
public void c()
{
txtIdR.Text = "";
txtPwdR.Text = "";
txtName.Text = "";
txtMail.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{//输入不能为空
if (txtIdR.Text == "" | txtPwdR.Text == "" | txtName.Text =="" | txtMail.Text == "")
{
MessageBox.Show("请输入完整信息");
return;
}
///LoginId不能为重复
//定义链接字符串
string connString = "Server=.;DataBase=Register;Uid=sa;Pwd=12345";
//创建连接对象
SqlConnection conn = new SqlConnection(connString);
//组合sql查询语句
string sqlSelect = "select id from RegisterInformation where id='"+txtIdR.Text.Trim()+"'";
SqlCommand cmd1 = new SqlCommand(sqlSelect, conn);
//执行查询
conn.Open();
object result1 = cmd1.ExecuteScalar();
//判断账号是否重复
if (result1!=null)
{
MessageBox.Show("该账户已被注册");
conn.Close();
return;
}
conn.Close();
//添加注册信息SQL语句
string sql = "insert into RegisterInformation(id,password,name,mail)";
sql += "values('{0}','{1}','{2}','{3}')";
sql = string.Format(sql, txtIdR.Text, txtPwdR.Text, txtName.Text, txtMail.Text);
SqlCommand cmd = new SqlCommand(sql, conn);
//打开连接
conn.Open();
//执行操作
int reslt = cmd.ExecuteNonQuery();
conn.Close();
//清空输入
c();
//注册成功
MessageBox.Show("注册成功");
this.Close();
}
//重置
private void button2_Click(object sender, EventArgs e)
{
c();
txtIdR.Focus();
}
}
}
登录窗体的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
}
private void btnLog_Click(object sender, EventArgs e)
{
//定义链接字符串
string connString = "Server=.;DataBase=Register;Uid=sa;Pwd=12345";
//创建连接对象
SqlConnection conn = new SqlConnection(connString);
string sqlLog = "select * from RegisterInformation where id='"+txtId.Text.Trim()+"'and password='"+txtPwd.Text.Trim()+"' ";
SqlCommand cmdL = new SqlCommand(sqlLog, conn);
conn.Open();
object resulta= cmdL.ExecuteScalar();
if (resulta!=null)
{
MessageBox.Show("登录成功");
}
else
{
MessageBox.Show("账号或密码错误,请重新输入");
}
conn.Close();
}
private void btnReg_Click(object sender, EventArgs e)
{
Register form2 = new Register();
form2.Show();
}
private void LoginForm_Load(object sender, EventArgs e)
{
this.ActiveControl = this.txtId;
}
private void LoginForm_Paint(object sender, PaintEventArgs e)
{
}
}
}