能够在c.Show()执行时显示数据库。当我关闭表单2并单击按钮6时,表单2上的gridview为空。知道如何修复这个错误吗?
表格1:
private void System_btn_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Bitmap picture = new Bitmap(openFileDialog1.FileName);
ZoneStatus c = new ZoneStatus();
c.dbname = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName);
//c.Show();
}
}
private void button6_Click(object sender, EventArgs e)
{
ZoneStatus zoneStatus_form = new ZoneStatus();
zoneStatus_form.Show();
}
表格2:
public string dbconnection;
public string dbname {get;set;}
private void ZoneStatus_Load(object sender, EventArgs e)
{
dbconnection = @"Data Source=" + dbname + ".db;Version=3;";
SQLiteConnection sqliteCon = new SQLiteConnection(dbconnection);
{
sqliteCon.Open();
// Create new DataAdapter
using (SQLiteDataAdapter a = new SQLiteDataAdapter(
"SELECT * FROM Alarm_Info", sqliteCon))
{
// Use DataAdapter to fill DataTable
DataTable dt = new DataTable();
a.Fill(dt);
dataGridView1.DataSource = dt; // to update my database
}
sqliteCon.Close();
}
}
答案 0 :(得分:0)
更改"公共字符串dbname" to" public static string dbname"。(如果你想使用那个变量,也与dbconnection相同。) 让我们假设您已经在from1中声明了您的字符串,并且您希望在form2中使用此字符串,因此您的代码将如下所示。
Form1中:
public static string dbname;
在form2中创建form1的对象并像这样访问此变量。
窗口2:
form1 objf1 = new form1();
string str=objf1.dbname;
现在你可以用变量dbname做任何你想做的事情。你可以像我一样分配给其他变量。