关闭窗体后刷新SQL

本文关键字:刷新 SQL 窗体 | 更新日期: 2023-09-27 18:24:27

我创建了一个将数据插入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();
                }
            }
        }

因此,基本上,当用户点击OK(submitButton)时,数据被插入,窗口被关闭,并且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中完全相同的代码来加载数据,并且它运行良好。

感谢您的帮助!

关闭窗体后刷新SQL

第二个表单似乎正在创建主表单的新实例。新实例永远不会显示。您需要获取现有的主表单以进行refreshCall。

在打开第二个表单时,可以在主表单上使用以下代码。

// the ShowDialog will open your second form and then you use your DialogResult 
//  from the second form to tell your main form to refresh the data
yourSecondForm openSecondForm = new yourSecondForm.ShowDialog();
if(openSecondForm.DialogResult == DialogResult.OK)
{
    refreshCall()
}

然后在你的最后一个区块中的第二个表单中:

finally
{
    //Close the connection
    if (conn.State != ConnectionState.Closed)
    {
        //Close the connection
    }
    //Close the window
    DialogResult = DialogResult.OK;
}