2014-01-23 18 views
2

我想從第2列的所有值寫入到一個列表:的DataGridView從列寫的所有值列出

List<string> list = new List<string>(); 
foreach (var item in dataGridView1.Rows) 
{ 
    list.Add(item.Cells[1].Value.ToString); 
} 

然而,這將返回一個錯誤。

+0

什麼是你所得到的錯誤,你應該索引列2,在當前的代碼你引用第一列。 – Habib

+0

哦,對,現在改正。錯誤是:''obejct'沒有包含'cells'的定義,也沒有擴展方法可以找到接受'object'類型的第一個參數的'Cells'(你是否缺少using指令或程序集引用?) 。' – jacobz

回答

8

對於錯誤:

'obejct' does not contain a definition for 'cells' and no extension method 'Cells' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?).

您需要修改foreach循環,而不是var指定DataGridViewRow

foreach (DataGridViewRow item in dataGridView1.Rows) 
{ 
    list.Add(item.Cells[1].Value.ToString()); 
} 

還需要()ToString

如果你想使用LINQ,那麼你可以做到這一點像一條語句:

List<string> list = dataGridView1.Rows 
          .OfType<DataGridViewRow>() 
          .Select(r => r.Cells[1].Value.ToString()) 
          .ToList(); 

編輯:

以上可能會導致一個空引用異常如果Cell[1]任何行的值是null你可以添加一個檢查,然後再添加它來檢查是否存在單元格以及它是否有價值。像:

List<string> list = new List<string>(); 
foreach (DataGridViewRow item in dataGridView1.Rows) 
{ 
    if (item.Cells.Count >= 2 && //atleast two columns 
     item.Cells[1].Value != null) //value is not null 
    { 
     list.Add(item.Cells[1].Value.ToString()); 
    } 
} 

上述檢查將從調用null對象上ToString救你,你不會得到例外。

+0

這會在'list.Add(item.Cells [1] .Value.ToString());''返回'System.NullReferenceException'。使用LINQ它會在'r.Cells [1] .Value.ToString()'' – jacobz

+0

@ Jacobus21返回相同的值,這意味着您的列中有一些行爲'null'值。讓我修改答案 – Habib

+0

@ Jacobus21,檢查編輯部分的答案 – Habib

0

發生錯誤是因爲Rows不會自動轉換爲DataGridViewRow當您使用var時。 正確的代碼是:

List<string> list = new List<string>(); 
foreach (DataGridViewRow row in dataGridView1.Rows) 
{ 
    list.Add(row .Cells[1].Value.ToString()); 
} 
1

要考慮使用LINQ空例外:

List<string> list = dataGridView1.Rows 
         .OfType<DataGridViewRow>() 
         .Where(x => x.Cells[1].Value != null) 
         .Select(x => x.Cells[1].Value.ToString()) 
         .ToList();