2011-11-23 122 views
0

我無法用字符串數組中的項填充datagridview。下面是我用來調用函數的代碼:C#將行添加到datagridview

ThreadPool.QueueUserWorkItem((o) => 
       ReBuildObjectExplorer(); 

和函數本身:

 try 
     { 
      List<ExplorerItem> list = new List<ExplorerItem>(); 
      var item = new ExplorerItem(); 

      for (int i = 0; i < lbl.Length; i++) // lbl = string array with items 
      { 
       item.title = lbl[i].Name; 
       list.Add(item); 
      } 

      BeginInvoke((MethodInvoker)delegate 
      { 
       explorerList = list; 
       dgvObjectExplorer.RowCount = explorerList.Count; 
       dgvObjectExplorer.Invalidate(); 
      }); 
     } 
     catch (Exception e) { MessageBox.Show(e.ToString(); } 

的問題是:假設有數組中的76項。當我使用這個代碼時,它總是添加76次第75項,沒有別的。爲什麼會發生?我似乎無法弄清楚我的代碼有什麼問題。

回答

1

我想你想:

try 
    { 
     List<ExplorerItem> list = new List<ExplorerItem>(); 

     for (int i = 0; i < lbl.Length; i++) // lbl = string array with items 
     { 
      var item = new ExplorerItem(); 
      item.title = lbl[i].Name; 
      list.Add(item); 
     } 

     BeginInvoke((MethodInvoker)delegate 
     { 
      explorerList = list; 
      dgvObjectExplorer.RowCount = explorerList.Count; 
      dgvObjectExplorer.Invalidate(); 
     }); 
    } 
    catch (Exception e) { MessageBox.Show(e.ToString(); } 

也就是說,移動循環中,而不是外面新ExplorerItem的創建。這樣,在循環的每次迭代中都會創建一個新項目。如果您在每次迭代中都不創建新項目,那麼您將一遍又一遍地添加相同的項目,並在每次迭代中更改其標題。

+0

謝謝。您發佈的代碼完美無瑕。 – david