Convert contents of DataGridView to List in C#

前端 未结 5 1358
再見小時候
再見小時候 2020-12-19 00:35

What is the best way to grab the contents of a DataGridView and place those values into a list in C#?

相关标签:
5条回答
  • 2020-12-19 00:49

    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();
    
    0 讨论(0)
  • 2020-12-19 00:50

    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 });
                        }
                    });
    
    0 讨论(0)
  • 2020-12-19 00:52
            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);
            }
    
    0 讨论(0)
  • 2020-12-19 01:02

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

    List<Class> myClass = DataGridView.DataSource as List<Class>;
    
    0 讨论(0)
  • 2020-12-19 01:10
    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();
    
    0 讨论(0)
提交回复
热议问题