.net 将DataGridView的内容转换为C#中的列表

bvk5enib  于 2022-12-01  发布在  .NET
关注(0)|答案(6)|浏览(142)

在C#中,获取DataGridView的内容并将这些值放入列表中的最佳方法是什么?

zzzyeukh

zzzyeukh1#

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);
        }
3b6akqbq

3b6akqbq2#

如果您使用DataSource系结清单,则可以使用下列方式转换回:

List<Class> myClass = DataGridView.DataSource as List<Class>;
v7pvogib

v7pvogib3#

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();
hpxqektj

hpxqektj4#

或者一条直线

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();
xxb16uws

xxb16uws5#

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 });
                    }
                });
dced5bon

dced5bon6#

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;

相关问题