【发布时间】:2010-11-25 21:54:02
【问题描述】:
在 C# 中获取 DataGridView 的内容并将这些值放入列表的最佳方法是什么?
【问题讨论】:
标签: c# list datagridview
在 C# 中获取 DataGridView 的内容并将这些值放入列表的最佳方法是什么?
【问题讨论】:
标签: c# list datagridview
List<MyItem> items = new List<MyItem>();
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
MyItem item = new MyItem();
foreach (DataGridViewCell dc in dr.Cells)
{
...build out MyItem....based on DataGridViewCell.OwningColumn and DataGridViewCell.Value
}
items.Add(item);
}
【讨论】:
如果您使用 DataSource 绑定您的列表,您可以通过以下方式转换回来:
List<Class> myClass = DataGridView.DataSource as List<Class>;
【讨论】:
var Result = dataGridView1.Rows.OfType<DataGridViewRow>().Select(
r => r.Cells.OfType<DataGridViewCell>().Select(c => c.Value).ToArray()).ToList();
或获取值的字符串字典
var Result = dataGridView1.Rows.OfType<DataGridViewRow>().Select(
r => r.Cells.OfType<DataGridViewCell>().ToDictionary(c => dataGridView1.Columns[c.OwningColumn].HeaderText, c => (c.Value ?? "").ToString()
).ToList();
【讨论】:
或linq方式
var list = (from row in dataGridView1.Rows.Cast<DataGridViewRow>()
from cell in row.Cells.Cast<DataGridViewCell>()
select new
{
//project into your new class from the row and cell vars.
}).ToList();
【讨论】:
IEnumerable.OfType<TResult> 扩展方法可以成为你最好的朋友。以下是我通过 LINQ 查询完成的方法:
List<MyItem> items = new List<MyItem>();
dataGridView1.Rows.OfType<DataGridViewRow>().ToList<DataGridViewRow>().ForEach(
row =>
{
foreach (DataGridViewCell cell in row.Cells)
{
//I've assumed imaginary properties ColName and ColValue in MyItem class
items.Add(new MyItem { ColName = cell.OwningColumn.Name, ColValue = cell.Value });
}
});
【讨论】:
VB:
Dim lst As List(Of DataGridViewRow) = Me.MasterDataGridView.Rows.Cast(Of DataGridViewRow).AsEnumerable.ToList
C#:
List<DataGridViewRow> lst = this.MasterDataGridView.Rows.Cast<DataGridViewRow>.AsEnumerable.ToList;
【讨论】: