[英]convert DataGridView Contents to Excel using SpreadSheetLight in C#
[英]Convert contents of DataGridView to List in C#
獲取 DataGridView 的內容並將這些值放入 C# 中的列表的最佳方法是什么?
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>;
或者是一種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();
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();
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.