2010-11-25 54 views

回答

12
 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

如果在foreach語句中我想訪問行中第一個元素的值,我該如何實現? – 2010-11-25 22:31:28

4

或者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(); 
3
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(); 
4

的字符串字典如果您在使用數據源綁定你的列表,你可以通過轉換回,

List<Class> myClass= DataGridView.Datasource as List<Class> ; 
0

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 }); 
        } 
       }); 
相關問題