我创建了一个将数据插入 SQL 数据库的应用程序。基本上,用户从主窗体打开第二个窗体,提示他们输入将进入数据库的数据。代码如下所示:
private void submitButton_Click(object sender, EventArgs e)
{
//Get form values
try
{
//Open test connection
}
catch (Exception ex)
{
//Handle errors
}
finally
{
//Close test connection
}
//Run the SQL statements
try
{
//Inser SQL data
}
catch (Exception ie)
{
//Handle errors
}
finally
{
//Close the connection
if (conn.State != ConnectionState.Closed)
{
//Close the connection
}
//Close the window
this.Close();
//Tell the main form to reload SQL data (not working)
mainForm firstForm;
firstForm = new mainForm();
firstForm.refreshCall();
}
}
}
基本上,当用户点击确定(提交按钮)时,数据被插入,窗口关闭,refreshCall() 方法被调用。我的方法“refreshCall”应该刷新在主窗体上输出的 SQL 数据,如下所示:
public void refreshCall()
{
SqlConnection conn = new SqlConnection("Data Source=SERVER\\SQL_DB;Initial Catalog=dataTable;Integrated Security=True");
try
{
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT part_num from dbo.Parts", conn);
adapter.Fill(ds);
this.listParts.DataSource = ds.Tables[0];
this.listParts.DisplayMember = "part_num";
conn.Close();
}
catch (SqlException odbcEx)
{
MessageBox.Show("There was an error connecting to the data source.\nError Code: 1001", "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
但是,调用此方法时,数据仍未刷新,这意味着我必须关闭应用程序并重新加载它才能看到我的更改。我的代码中是否有什么地方做错了导致 SQL 数据保持不变?有一个更好的方法吗?我还应注意,我使用 refreshCall 中完全相同的代码在初始化表单时加载数据,并且工作正常。
感谢任何帮助!
请您参考如下方法:
看起来第二个窗体正在创建主窗体的新实例。新实例永远不会显示。您需要为 refreshCall 获取现有的主表单。
