2010-06-06 78 views
1

我想從兩個單獨的線程向DataGridView添加行。我嘗試了一些代表和BeginInvoke,但不起作用。從線程向DataGridView添加行

這是我的行更新函數,它是從線程中的另一個函數調用的。

public delegate void GRIDLOGDelegate(string ulke, string url, string ip = ""); 
    private void GRIDLOG(string ulke, string url, string ip = "") 
    { 

     if (this.InvokeRequired) 
     { 
      // Pass the same function to BeginInvoke, 
      // but the call would come on the correct 
      // thread and InvokeRequired will be false. 
      object[] myArray = new object[3]; 

      myArray[0] = ulke; 
      myArray[1] = url; 
      myArray[2] = ip; 

      this.BeginInvoke(new GRIDLOGDelegate(GRIDLOG), 
              new object[] { myArray }); 

      return; 
     } 

     //Yeni bir satır daha oluştur 
     string[] newRow = new string[] { ulke, url, ip }; 
     dgLogGrid.Rows.Add(newRow); 
    } 
+0

它是如何不工作?它是否編譯?你有什麼例外嗎? – 2010-06-06 23:06:09

回答

1
this.BeginInvoke(new GRIDLOGDelegate(GRIDLOG), 
     //error seems to be here -> new object[] { myArray }); 
     myArray) // <- how it should be 

更新:

你也可以這樣來做:

BeginInvoke(new GRIDLOGDelegate(GRIDLOG), ulke, url, ip); 
1

你需要傳遞的參數數組。 你犯了一個錯誤,同時呼籲this.BeginInvoke

嘗試這樣的:

this.BeginInvoke(new GRIDLOGDelegate(GRIDLOG), new object[] { ulke, url, ip }); 

一切似乎是正確的。

1

希望這是有益=]

private object[] DatagridBuffer(Person p) 
{ 
    object[] buffer = new object[1]; 
    buffer[0] = p.FirstName; 
    buffer[1] = p.LastName; 
    return buffer; 
{ 

public void ListPeople() 
{ 
    List<DatagridViewRow> rows = new List<DataGridViewRow>(); 
    Dictionary<int, Person> list = SqlUtilities.Instance.InstallationList(); 
    int index = 0; 
    foreach (Person p in list.Values) { 
     rows.Add(new DataGridViewRow()); 
     rows[index].CreateCells(datagrid, DatagridBuffer(p)); 
     index += 1; 
    } 
    UpdateDatagridView(rows.ToArray()); 
} 

public delegate void UpdateDatagridViewDelegate(DataGridViewRow[] list); 
public void UpdateDatagridView(DataGridViewRow[] list) 
{ 
    if (this.InvokeRequired) 
    { 
     this.BeginInvoke(
      new UpdateDatagridViewDelegate(UpdateDatagridView), 
      new object[] { list } 
     ); 
    } 
    else 
    { 
     datagrid.Rows.AddRange(list); 
    } 
} 

如果你發現我的代碼不正確,或者可以改進,請做評論。

2

您可以使用下面的代碼:

private void GRIDLOG(string ulke, string url, string ip = "") 
    { 
     object[] myArray = new object[] { ulke, url, ip}; 
     if (this.InvokeRequired) 
      dgLogGrid.Invoke((MethodInvoker)(() => dgLogGrid.Rows.Add(myArray))); 
     else dgLogGrid.Rows.Add(myArray); 
    }