表单关闭后刷新SQL

时间:2012-02-14 17:42:18

标签: c# sql winforms

我创建了一个将数据插入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中完全相同的代码在表单初始化时加载数据,并且工作正常。

感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

似乎第二种形式是创建主窗体的新实例。永远不会显示新实例。您需要为refreshCall获取现有的主表单。

答案 1 :(得分:1)

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

// 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块中的第二种形式:

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