无法弄清楚为什么getConnectionString不断传递NULL

时间:2018-11-15 11:59:37

标签: c# database forms class

我正在尝试将我的连接字符串从一种形式转换为另一种形式,但它始终传递NULL Im,这是使用不同类的新知识,因此这可能是一个非常简单的错误。

表格1

JobScheduler

表格2

public partial class Form1 : Form
{
    private string ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Ruben\Documents\dbPlatenCompany.mdf;Integrated Security = True; Connect Timeout = 30";
    public Form1()
    {
        InitializeComponent();
    }

    public string getConnectionString()
    {
        return ConnectionString;
    }

    private void btn_login_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConnectionString);
        SqlDataAdapter sqa = new SqlDataAdapter("Select count(*) From tblLogin where Username ='" + txt_username.Text + "' and Password ='" + txt_password.Text + "'", con);
        DataTable dt = new DataTable();
        sqa.Fill(dt);

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

        else
        {
            MessageBox.Show("Username or Password is incorrect");
            txt_username.Clear();
            txt_password.Clear();
        }
    }
}

2 个答案:

答案 0 :(得分:3)

这是因为您从未真正在Form2中初始化Form1。

private Form1 form1;更改为private Form1 form1 = new Form1();

答案 1 :(得分:-1)

公共静态字符串ConnectionString = @“数据源=(LocalDB)\ MSSQLLocalDB; AttachDbFilename = C:\ Users \ Ruben \ Documents \ dbPlatenCompany.mdf;集成安全性= True;连接超时= 30”;

在Form2中使用 不创建form1对象

String ConnectionString = form1.ConnectionString

此变量尝试解决此问题