在避免System.NullReferenceException ERROR的同时传递值

时间:2017-12-14 17:10:47

标签: c# sql database login error-handling

如何在没有System.NullReferenceException ERROR的情况下,在登录到另一个表单时传递User输入的值?

我使用类来帮助将值从一个表单传递到另一个表单,类代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StudentFollowUp
{
    public class Student
    {
        public string username { get; set; }
        public string password { get; set; }
    }
}

然后我做了一个登录页面,用户可以输入他的用户名和密码,我与数据库建立连接,当我运行下面的代码时,我得到这句话:"类型&#的未处理异常39; System.NullReferenceException'发生在StudentFollowUp.exe

附加信息:未将对象引用设置为对象的实例。"

以下是代码,并提前感谢:

private void loginlable_click(object sender, EventArgs e)
        {
            using (SqlConnection Connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\StudentFollowup.mdf;Integrated Security=True;"))
            {
                SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From Users Where Username = '" + username.Text + "' and Password = '" + password.Text + "'", Connection);
                DataTable dt = new DataTable();

                StudentInfo.username = username.Text;
                StudentInfo.password = password.Text;

                sda.Fill(dt);

                if (dt.Rows[0][0].ToString() == "1")
                {
                    this.Hide();
                    Main ss = new Main();
                    ss.Show();
                }

                else
                {
                    MessageBox.Show("Please Check Your Username and Password");
                }       

            }
}

0 个答案:

没有答案