獲取DataGridView的內容並將這些值放入C#列表中的最佳方式是什麼?將DataGridView的內容轉換爲C#中的列表#
9
A
回答
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);
}
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 });
}
});
相關問題
- 1. 使用C#中的SpreadSheetLight將DataGridView內容轉換爲Excel#
- 2. 將HTML內容轉換爲列表
- 3. 將C#datagridview列轉換爲數組
- 4. 將列表轉換爲xml中的c#
- 5. 在MySQL Datagridview中將單元格內容轉換爲超鏈接
- 6. 使用列表內容過濾datagridview C#
- 7. 無法將argv []中的內容轉換爲C中的float [] [] 0
- 8. 基於Oracle 10g中的內容將列轉換爲列PL/SQL
- 9. 將具有分隔內容的textarea轉換爲實體列表
- 10. 將轉換列表<Cookie>轉換爲C#中的CookieCollection
- 11. C#Datagridview - 將TextColumn轉換爲ComboBoxColumn
- 12. 如何將X列表轉換爲C#中的Y列表?
- 13. 將列表中的asp.net mvc c#列表轉換爲javascript數組
- 14. 將頁面內容轉換爲C#ASP.net中的MS詞
- 15. 如何在C++中將「string *」的內容轉換爲「const string&」?
- 16. 在c#中將word文件的內容轉換爲JPEG#
- 17. 將轉換列表轉換爲水星中的元組列表
- 18. 將篩選的DataGridView轉換爲C#中的DataTable
- 19. 將Excel工作表的內容轉換爲表格格式的C#腳本
- 20. TinyMCE將內容強制轉換爲有序列表(ol)
- 21. 如何將特定的datagridview列值轉換爲c#中的double值?
- 22. C#將列轉換爲列表中的一行
- 23. 將3D陣列轉換爲C中的列表#
- 24. 將JSON對象轉換爲C#列表
- 25. 將Python列表理解轉換爲C++?
- 26. 如何將字符串內的列表轉換爲列表
- 27. 將行錶轉換爲mysql中的列
- 28. 將DataModel轉換爲Java中的列表
- 29. 將列表轉換爲Python中的* args
- 30. 如何將UTC datetime列轉換爲datagridview中的本地時間?
如果在foreach語句中我想訪問行中第一個元素的值,我該如何實現? – 2010-11-25 22:31:28