Skip to main content
 首页 » 编程设计

c#之转换数据 GridView

2024年02月06日18虾米哥

我有以下代码:

foreach (DataGridViewRow row in dataGridView1.SelectedCells) 
{ 
    textBox1.Text += row.Cells[1].Value; 
} 

您可能会说我正在尝试根据 dataGridView 的选定行遍历特定列。但它在以下行中给我一个错误:

foreach (DataGridViewRow row in dataGridView1.SelectedCells) 

错误是:

Additional information: Unable to cast object of type 'System.Windows.Forms.DataGridViewTextBoxCell' to type 'System.Windows.Forms.DataGridViewRow'. 

请您参考如下方法:

要么使用

 foreach (DataGridViewRow row in dataGridView1.SelectedRows) 

或者,如果您需要从选定的单元格中获取行:

foreach (DataGridViewCell cell in dataGridView1.SelectedCells) 
{ 
   DataGridViewRow row = dataGridView1.Rows[cell.RowIndex]; 
   .. 
} 

在你的情况下,第一个解决方案似乎是正确的,(就像 Aaron 写的那样。)

请注意这两种解决方案都存在一两个问题:

第一个解决方案不会得到自然的排序顺序,除非用户注意遵循奇怪的窗口选择规则..

用这个来解决那个问题:

var selectedRowsOrdered = DGV.SelectedRows.Cast<DataGridViewRow>().OrderBy(c => c.Index); 
 
foreach (DataGridViewRow row in selectedRowsOrdered ) textBox1.Text += row[1].Value; 

在第二种解决方案中,使用 SelectedCells 集合,您还可能有重复项。

也可以使用这个小Linq 来摆脱它们:

var selectedRowsOrdered = DGV.SelectedCells.Cast<DataGridViewCell>() 
                         .Select(c => c).OrderBy(c => c.RowIndex).GroupBy(c => c); 
 
foreach (DataGridViewRow row in selectedRowsOrdered ) textBox1.Text += row[1].Value;