2012-02-03 63 views
0

我在计算这一项时遇到了一些问题。我对C#相当陌生,但我觉得这个答案应该很简单。在主表单上显示新插入的SQL数据

我有一个窗体显示它从SQL数据库中提取的数据。用户可以打开一个新窗口并向数据库中添加新条目,当他们单击确定时,信息将被插入到数据库中,并关闭窗口。

问题是,一旦发生这种情况,显示在主窗体上的信息不会显示刚输入的数据。我试图添加一个函数,在用户提交时刷新主窗体,但新信息不会显示。

有没有人有任何想法如何让新插入的SQL数据显示在主窗体上?这里是我参考的代码:

 try 
     { 
      conn.Open(); 
      SqlCommand myCommand = new SqlCommand("INSERT INTO customParts (part_num, date, customer, orig_call, vendor, vendor_pn, price, delivery, packaging, notes) VALUES (@partnum, @getdate, @cust, @callout, @vend, @vend_PN, @cost, @deliv, @pkging, @notes)", conn); 
      myCommand.Parameters.AddWithValue("@partnum", partnum); 
      myCommand.Parameters.AddWithValue("@getdate", getdate); 
      myCommand.Parameters.AddWithValue("@cust", cust); 
      myCommand.Parameters.AddWithValue("@vend", vend); 
      myCommand.Parameters.AddWithValue("@callout", callout); 
      myCommand.Parameters.AddWithValue("@vend_PN", vend_PN); 
      myCommand.Parameters.AddWithValue("@cost", cost); 
      myCommand.Parameters.AddWithValue("@deliv", deliv); 
      myCommand.Parameters.AddWithValue("@pkging", pkging); 
      myCommand.Parameters.AddWithValue("@notes", notes); 
      myCommand.ExecuteNonQuery(); 
     } 
     catch (Exception ie) 
     { 
      MessageBox.Show(ie.Message); 
     } 
     finally 
     { 
      //Close the connection 
      conn.Close(); 
      //Reload the main window to show new changes 
      mainForm firstForm; 
      firstForm = new mainForm(); 
      //Close the window 
      this.Close(); 
     } 

谢谢!

编辑:

我尝试添加这个方法到我的主要形式有:

public static void refreshThis() 
{ 
    Form mainForm = new mainForm(); 
    mainForm.Refresh(); 
} 

并调用它像这样:

 finally 
     { 
      //Close the connection 
      if (conn.State != ConnectionState.Closed) 
      { 
       conn.Close(); 
      } 
      mainForm.refreshThis(); 
      this.Close(); 
     } 

但它仍然似乎并没有工作?

+0

我假设这是针对Winforms而不是ASP.NET(标记的)。 – 2012-02-03 17:31:40

+0

是的,对不起,谢谢! – 2012-02-03 17:38:57

+1

如果(conn.State!= ConnectionState.Close)conn.Close();如果连接未关闭,则避免异常检查。 – Lloyd 2012-02-03 17:43:11

回答

3

在你的代码有以下几行:

mainForm firstForm; 
firstForm = new mainForm(); 

虽然这些线路将创建一个新的形式,这将被更新,它将尽快离开finally块和销毁用户不会看到它。

我想你真正想要的是在你的mainForm类暴露Refresh方法,并从子窗体调用它。

+0

好吧,我试过这个,但仍然无法让它工作。也许我以错误的方式解决了这个问题?我在我的帖子末尾添加了我所做的。 – 2012-02-03 18:09:50

+0

您还在创建'mainForm'的新实例。您需要刷新用户已打开的实例。 – 2012-02-03 18:12:08

相关问题