我創建了一個將數據插入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
中的完全相同的代碼在表單初始化時加載數據,並且它工作正常。
任何幫助表示讚賞!
當你通過調試步驟 - 是你的SQL插入代碼被刷新調用之前叫什麼名字?另外 - 你可以發佈你的SQL插入代碼嗎?這可能是連接/交易正確完成...... – tsells 2012-02-14 17:46:00