开发者

Convert contents of DataGridView to List in C#

开发者 https://www.devze.com 2023-01-27 13:10 出处:网络
What is the best way to g开发者_Go百科rab the contents of a DataGridView and place those values into a list in C#?List<MyItem> items = new List<MyItem>();

What is the best way to g开发者_Go百科rab the contents of a DataGridView and place those values into a list in 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);
        }


If you bind your list using DataSource, you can convert back by with:

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

or to get a string dictionary of the values

var Result = dataGridView1.Rows.OfType<DataGridViewRow>().Select(
            r => r.Cells.OfType<DataGridViewCell>().ToDictionary(c => dataGridView1.Columns[c.OwningColumn].HeaderText, c => (c.Value ?? "").ToString()
                ).ToList();


Or a linq way

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> extension method can be your best friend here. Here is how I would have done it through a LINQ query:

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号