问题遇到的现象和发生背景
用C#做一个可以连接数据库的登录页面
用代码块功能插入代码,请勿粘贴截图
readonly string Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString; //创建数据库连接
public static string username; //设置Form1的一个参数,登录成功后将显示在主界面Form3
public static string password;
private void Button1_Click(object sender, EventArgs e) //登录代码
{
SqlConnection conn = new SqlConnection(Stu); //创建数据库游标对象conn
conn.Open(); //打开数据库
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "select * from 登录注册表 where username='" + textBox1.Text.Trim() + "'";
SqlDataReader sdt = cmd.ExecuteReader();
if (textBox1.Text == "")
{
MessageBox.Show("账号不得为空!", "提示");
this.ActiveControl = textBox1;
}
else if (textBox2.Text == "")
{
MessageBox.Show("密码不得为空!", "提示");
this.ActiveControl = textBox2;
}
else if (sdt.Read() == true) //读取到记录
{
string result = sdt.GetString(sdt.GetOrdinal("password"));
if (MD5Encrypt(textBox2.Text.Trim(), textBox1.Text.Trim()) == result)
{
MessageBox.Show("登录成功!", "提示");
username = textBox1.Text.Trim(); //将textBox1的值赋给参数username
password = textBox2.Text.Trim(); //将textBox2的值赋给参数password
conn.Close(); //关闭数据库连接
this.Hide(); //隐藏当前窗口
Form3 sd = new Form3();
sd.Show(); //显示主界面Form3
}
else
{
MessageBox.Show("账号密码错误!", "提示");
textBox2.Text = "";
this.ActiveControl = textBox2;
}
}
else
{
DialogResult dr = MessageBox.Show("账号不存在,是否选择注册一个新账号?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (dr == DialogResult.OK)
{
this.Hide();
Form2 er = new Form2();
er.Show();
conn.Close();
}
else
{
textBox1.Text = "";
textBox2.Text = "";
this.ActiveControl = textBox1;
}
}
conn.Close(); //关闭游标对象连接
}
运行结果及报错内容
readonly string Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString; //创建数据库连接
本行报错:System.NullReferenceException:“未将对象引用设置到对象的实例。”
System.Configuration.ConnectionStringSettingsCollection.this[string].get 返回 null。
我的解答思路和尝试过的方法
把
this.button1.Font = new System.Drawing.Font("宋体", 15F);
this.button1.Location = new System.Drawing.Point(287, 232);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(118, 38);
this.button1.TabIndex = 5;
this.button1.Text = "登录";
this.button1.UseVisualStyleBackColor = true;
改成
this.button1.Font = new System.Drawing.Font("宋体", 15F);
this.button1.Location = new System.Drawing.Point(287, 232);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(118, 38);
this.button1.TabIndex = 5;
this.button1.Text = "登录";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click1);
运行不了
我想要达到的结果
我想知道怎样解决这个问题