我有两种表单Form1
和Form2
。 Form1
上有DataTable
,它连接到MySql
数据库。我在Form1
上创建了一个新的呼叫,然后打开Form2
,其中有一些字段需要填写。然后按保存呼叫,这会更新数据库。
我遇到的问题是它何时保存到数据库并关闭Form2
它没有出现在Form1
上,除非我关闭程序并重新打开它。如何让DataTable
刷新?
以下是Form1
代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string connectionString = "datasource=localhost;database=***;username=***;password=***;";
string query = "select call_ref, opened, contact, it, summary from helpdesks;";
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = command;
DataTable dTable = new DataTable();
adapter.Fill(dTable);
dataGridView1.DataSource = dTable;
connection.Close();
}
public void viewData(object sender, DataGridViewCellEventArgs e)
{
Form2 secondForm = new Form2();
secondForm.Show();
string connectionString = "datasource=localhost;***;username=***;password=***;";
string query = "select * from users where id = " + this.dataGridView1.CurrentRow.Cells[0].Value + ";";
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
secondForm.textBox1.Text = reader.GetString("call_ref");
}
connection.Close();
}
private void newCallBtn_Click(object sender, EventArgs e)
{
Form2 secondForm = new Form2();
secondForm.Show();
}
}
这是我的Form2
代码:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void saveCallBtn_Click(object sender, EventArgs e)
{
string connectionString = "datasource=localhost;database=***;username=***;password=***;";
string query = "INSERT INTO helpdesks(contact, opened)VALUES('" + textBox2.Text + "',STR_TO_DATE('" + DateTime.Now + "','%d/%m/%Y %h:%i:%s %p'));";
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand command = new MySqlCommand(query, connection);
MySqlDataReader reader;
connection.Open();
reader = command.ExecuteReader();
MessageBox.Show("Call Saved");
connection.Close();
}
}
答案 0 :(得分:0)
您可以使用FormClosedEventArgs。
private void newCallBtn_Click(object sender, EventArgs e)
{
Form2 secondForm = new Form2();
secondForm.FormClosed += new FormClosedEventHandler(Form2_Closed);
secondForm.Show();
}
在Form1中添加:
private void Form2_Closed(object sender, FormClosedEventArgs e)
{
// here update DataTable
}