C# 无法理解getConnectionString为什么一直传递NULL
我试图将我的连接字符串从一个表单传递到另一个表单,但它不断传递NULL,这是我处理不同类的新手,所以这可能是一个非常简单的错误 表格一C# 无法理解getConnectionString为什么一直传递NULL,c#,database,forms,class,C#,Database,Forms,Class,我试图将我的连接字符串从一个表单传递到另一个表单,但它不断传递NULL,这是我处理不同类的新手,所以这可能是一个非常简单的错误 表格一 public partial class Form1 : Form { private string ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Ruben\Documents\dbPlatenCompany.mdf;Integrate
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();
}
}
}
表格二
public partial class Form2 : Form
{
private Form1 form1;
public Form2()
{
InitializeComponent();
}
private void btn_search_Click(object sender, EventArgs e)
{
if (rb_Artist.Checked == true)
{
String ConnectionString = form1.getConnectionString();
SqlConnection con = new SqlConnection(ConnectionString);
SqlDataAdapter sqa = new SqlDataAdapter("SELECT * FROM tblArtist where Name like" + txt_search.Text, con);
DataTable dt = new DataTable();
sqa.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
这是因为您从未在Form2中实际初始化Form1
更改
私有表单1表单1
toprivate Form1 Form1=new Form1()代码>公共静态字符串连接字符串=@“数据源=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Ruben\Documents\dbPlatenCompany.mdf;集成安全性=True;连接超时=30”
使用表格2
不创建form1对象
字符串ConnectionString=form1.ConnectionString
这个变量试图解决这个问题什么是null
?将private string
更改为private const string
。可能是重复的感谢,我尝试了一个多小时后才意识到!如果您想在几个表单或类中使用连接字符串之类的变量,请在app.config文件中配置它们,这也没问题。您可以更轻松地访问和更改它们,而不是在表单之间传递它们。