2012-02-10 117 views
1

我一直試圖讓這個工作一段時間,但不能(我對C#和OOP一般而言是相當新的)。來自子窗體的父窗體上的調用方法

基本上,我有這一塊的第二碼形式:

private void button1_Click(object sender, EventArgs e) 
{ 
    if (charCount > 2 && charCount < 30) 
    { 
     try 
     { 
      conn.Open(); 
     } 
     catch (Exception ex) 
     { 
     //Error handling code here 
     } 
     finally 
     { 
      conn.Close(); 
     } 
     //Run the SQL statements 
     try 
     { 

     //SQL insert data is here 

     } 
     catch (Exception ie) 
     { 
      MessageBox.Show(ie.Message); 
     } 
     finally 
     { 
      //Close the connection 
      if (conn.State != ConnectionState.Closed) 
      { 
       conn.Close(); 
      } 

      mainForm.refreshCall(); 

      this.Close(); 
     } 

    } 
    else 
    { 
     MessageBox.Show("Part numbers can be between 2 and 30 characters.\n Yours was " + charCount + " characters long.", "Error"); 
    } 

} 

這一切都運行正常,並做什麼它應該,這是一些數據插入到一個SQL數據庫(我把代碼出使它更清潔一點)。所以發生這一切後,我嘗試執行mainForm.refreshCall()。這refreshCall方法存在我的第一個表格上,或mainForm,看起來像這樣:

public static void refreshCall() 
{ 
    SqlConnection conn = new SqlConnection("Data Source=DSERVER\\NEW_SQL;Initial Catalog=AWSoftware;Integrated Security=True"); 
    try 
    { 
     conn.Open(); 
     DataSet ds = new DataSet(); 
     SqlDataAdapter adapter = new SqlDataAdapter("SELECT part_num from dbo.CustomParts", 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); 
    } 
} 

然而,this.listParts.DataSourcethis.listParts.DisplayMember都告訴我,他們是無效的靜態屬性錯誤,靜態方法或靜態字段初始化。我對這意味着什麼感到困惑。如果有人願意爲我闡明這一點,我將不勝感激!

回答

0

您的refreshCall被標記爲static,但是您正在引用實例化變量,在這種情況下,您的ListBox將不起作用。您必須傳入ListBox作爲參數引用,或者只刪除static屬性。

最簡單的方法:

public void refreshCall() { 
    // blah-blah 
} 

然後調用該方法的變化:

this.refreshCall(); 
+0

當我改變調用this.RefreshCall()我得到「Program.addPart」不包含一個定義對於'refreshCall'並且沒有擴展方法'refreshCall'接受'Program.addPart'類型的第一個參數可以找到(你是否缺少使用指令或程序集引用?)「 – 2012-02-10 21:36:38

+0

@AndrewDeoreore」this.refreshCall()「從'MainForm'形式內工作,因爲這就是'this'的作用去。如果程序中的另一個表單正在嘗試進行該調用,則需要引用您正在使用的MainForm,例如myForm,在這種情況下,它將是'myForm.refreshCall()'。希望這是有道理的。 – LarsTech 2012-02-10 21:45:17

+0

是的,這確實是有道理的,實際上它最初是我嘗試做的,但是後來我收到一條消息,說「對象引用是非靜態字段,方法或屬性所必需的」。 – 2012-02-10 22:11:53

相關問題