在主窗体上显示新插入的SQL数据
本文关键字:插入 SQL 数据 窗体 显示 新插入 | 更新日期: 2023-09-27 18:22:20
我在弄清楚这个问题时遇到了一点小麻烦。我对C#还很陌生,但我觉得这个问题的答案应该很简单。
我有一个表单,它显示从SQL数据库中提取的数据。用户可以打开一个新窗口并向数据库中添加新条目,当他们单击"确定"时,信息就会插入数据库,窗口就会关闭。
问题是,一旦发生这种情况,主窗体上显示的信息就不会显示刚刚输入的数据。我试图添加一个函数,当用户提交时刷新主表单,但新信息不会显示。
有人知道如何将新插入的SQL数据显示在主窗体上吗?这是我的代码供参考:
try
{
conn.Open();
SqlCommand myCommand = new SqlCommand("INSERT INTO customParts (part_num, date, customer, orig_call, vendor, vendor_pn, price, delivery, packaging, notes) VALUES (@partnum, @getdate, @cust, @callout, @vend, @vend_PN, @cost, @deliv, @pkging, @notes)", conn);
myCommand.Parameters.AddWithValue("@partnum", partnum);
myCommand.Parameters.AddWithValue("@getdate", getdate);
myCommand.Parameters.AddWithValue("@cust", cust);
myCommand.Parameters.AddWithValue("@vend", vend);
myCommand.Parameters.AddWithValue("@callout", callout);
myCommand.Parameters.AddWithValue("@vend_PN", vend_PN);
myCommand.Parameters.AddWithValue("@cost", cost);
myCommand.Parameters.AddWithValue("@deliv", deliv);
myCommand.Parameters.AddWithValue("@pkging", pkging);
myCommand.Parameters.AddWithValue("@notes", notes);
myCommand.ExecuteNonQuery();
}
catch (Exception ie)
{
MessageBox.Show(ie.Message);
}
finally
{
//Close the connection
conn.Close();
//Reload the main window to show new changes
mainForm firstForm;
firstForm = new mainForm();
//Close the window
this.Close();
}
谢谢!
编辑:
我试着把这个方法添加到我的主表单中:
public static void refreshThis()
{
Form mainForm = new mainForm();
mainForm.Refresh();
}
并这样称呼它:
finally
{
//Close the connection
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
mainForm.refreshThis();
this.Close();
}
但它似乎仍然不起作用?
在代码中有以下几行:
mainForm firstForm;
firstForm = new mainForm();
虽然这些行将创建一个新的表单,该表单将被更新,但一旦你离开finally块,它就会被销毁,用户将永远看不到它
我认为您真正想要的是在mainForm
类中公开一个Refresh
方法,并从子窗体中调用它。