2013-09-27 63 views
1

我想更新與不同類和線程計算一些數據一個DataGridView,使用委託另一個線程更新GUI的datagridview。不幸的是,我遇到了各種不同的錯誤,具體取決於我嘗試的方法。C# - 使用委託

我想要的形式線程來執行代碼如下所示:

public partial class AcquireForm : Form 
// 
// ... 
// 
    // update the grid with results 
    public delegate void delUpdateResultsGrid(int Index, Dictionary<string, double> scoreCard); 
    public void UpdateResultsGrid(int Index, Dictionary<string, double> scoreCard) 
    { 
     if (!this.InvokeRequired) 
     { 
      // 
      // Some code to sort the data from scoreCard goes here 
      // 

      DataGridViewRow myRow = dataGridViewResults.Rows[Index]; 
      DataGridViewCell myCell = myRow.Cells[1]; 
      myCell.Value = 1; // placeholder - the updated value goes here 
      } 
     } 
     else 
     { 
      this.BeginInvoke(new delUpdateResultsGrid(UpdateResultsGrid), new object[] { Index, scoreCard}); 
     } 
    } 

現在,我需要得到這個方法從我的其他線程,類運行。我曾嘗試:

public class myOtherClass 
// 
// ... 
// 

    private void myOtherClassMethod(int myIndex) 
    { 
     // ... 
     AcquireForm.delUpdateResultsGrid updatedelegate = new AcquireForm.delUpdateResultsGrid(AcquireForm.UpdateResultsGrid); 
     updatedelegate(myIndex, myScoreCard); 
    } 

不幸的是這給出了一個「對象引用是所必需的非靜態字段,方法或屬性AcquireForm.UpdateResultsGrid(INT,System.Collections.Generic.Dictionary)」錯誤。我似乎無法在所有引用UpdateResultsGrid方法...

我注意到,

public class myOtherClass 
// 
// ... 
// 

    private void myOtherClassMethod(int myIndex) 
    { 
     // ... 
     AcquireForm acquireForm = new AcquireForm(); 
     acquireForm.UpdateResultsGrid(myIndex,myScoreCard); 
    } 

不會引發編譯時錯誤,但它試圖創建一個新的形式,那是後話我不想做。我不想創建一個AcquireForm的新實例,我想引用預先存在的實例,如果可能的話。

我也試圖使UpdateResultsGrid方法靜態的,但這拋出了問題,幾件事情incuding使用「這一點。(什麼)」。

我也試着動了廣大UpdateResultsGrid方法爲myOtherClassMethod,在AcquireForm類只是委託留下。同樣,這不起作用,因爲許多對UI對象的引用中斷(在範圍內沒有任何dataGridViews)。

我開始的想法在這裏運行。不幸的是我是相當新的C#(如你可能知道),和我編輯別人的代碼,而不是完全從頭開始寫我自己。如果任何人都可以提供一些關於這個問題的建議,那將是非常感謝。

回答

0

確保您對象相互溝通:你myOtherClass將不得不瞭解的AcquireForm對象 - 你不能只是建立一個新的(如你發現)。你需要的AcquireForm 對象傳遞到myOtherClass 對象(myOtherObject.SetForm(myAcquireForm,例如),並引用它,當你需要。

在您遇到與調用這個實力問題時是的幫助 - 我如何調用「下一步」按鈕點擊:

BeginInvoke(new Action(()=>button_next_Click(null,null))); 

此外,聽起來或許這不應該是單獨的類,你應該利用BackgroundWorkder代替

+0

嗨noelicus,非常感謝。花時間幫忙我與此。你能稍微闡述一下嗎?我嘗試添加一行: [代碼] myOtherClass.SetForm(AcquireForm); [/代碼] 但沒有奏效 - SetForm似乎並沒有被承認爲一個有效的定義。我同意,我需要得到承認AcquireForm對象myOtherClass,但你能提供一些意見,如何做到這一點? – user2823789

+0

你需要確保你*對象*正在溝通 - 你輸入的內容意味着你可能會很好地閱讀類和對象之間的區別。另外,我建議你試着從你所說的內容中做出你所擁有的一堂課,然後這些問題就會消失。 – noelicus

+0

好的,我想我已經破解了它。我爲類型爲AcquireForm的myOtherClass的構造函數添加了一個字段,然後在從AcquireForm創建類的實例時使用「this」。這似乎現在沒有錯誤,但我會考慮合併類,當我有一點點時間。 非常感謝您的建議! – user2823789