我想從第2列的所有值寫入到一個列表:的DataGridView從列寫的所有值列出
List<string> list = new List<string>();
foreach (var item in dataGridView1.Rows)
{
list.Add(item.Cells[1].Value.ToString);
}
然而,這將返回一個錯誤。
我想從第2列的所有值寫入到一個列表:的DataGridView從列寫的所有值列出
List<string> list = new List<string>();
foreach (var item in dataGridView1.Rows)
{
list.Add(item.Cells[1].Value.ToString);
}
然而,這將返回一個錯誤。
對於錯誤:
'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
救你,你不會得到例外。
發生錯誤是因爲Rows
不會自動轉換爲DataGridViewRow
當您使用var
時。 正確的代碼是:
List<string> list = new List<string>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
list.Add(row .Cells[1].Value.ToString());
}
要考慮使用LINQ空例外:
List<string> list = dataGridView1.Rows
.OfType<DataGridViewRow>()
.Where(x => x.Cells[1].Value != null)
.Select(x => x.Cells[1].Value.ToString())
.ToList();
什麼是你所得到的錯誤,你應該索引列2,在當前的代碼你引用第一列。 – Habib
哦,對,現在改正。錯誤是:''obejct'沒有包含'cells'的定義,也沒有擴展方法可以找到接受'object'類型的第一個參數的'Cells'(你是否缺少using指令或程序集引用?) 。' – jacobz