2012-02-14 86 views
1

我創建了一個將數據插入SQL數據庫的應用程序。基本上,從主窗體中,用戶打開第二個窗體,提示他們輸入數據庫中的數據。代碼如下所示:關閉窗體後刷新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(提交按鈕),將數據插入,窗口被關閉,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

當你通過調試步驟 - 是你的SQL插入代碼被刷新調用之前叫什麼名字?另外 - 你可以發佈你的SQL插入代碼嗎?這可能是連接/交易正確完成...... – tsells 2012-02-14 17:46:00

回答

3

看起來第二種形式是創建主窗體的新實例。新實例永遠不會顯示。您需要爲您的refreshCall獲取現有的主窗體。

+0

如何讓它在現有表單上調用refreshCall(而不是創建新表單)? – 2012-02-14 18:32:18

+0

完全想念他創造一個新的實例 - 好趕上... – tsells 2012-02-14 18:36:21

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; 
}