【问题标题】:Casting a datagridview铸造一个datagridview
【发布时间】:2015-05-21 10:10:04
【问题描述】:

我有以下代码:

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'.

【问题讨论】:

    标签: c# visual-studio-2013 datagridview .net-3.5 c#-3.0


    【解决方案1】:

    随便用

     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;
    

    【讨论】:

      【解决方案2】:

      在您的 foreach 中,您尝试创建一个 DataGridViewRow,但从 DataGridViewCell 的集合中请求它,这就是您收到错误的原因。而是在 foreach 中使用 DataGridViewCell ,然后使用单元格到达行:

      foreach (DataGridViewCell cell in dataGridView1.SelectedRows)
      {
          textBox1.Text += cell.OwningRow.Cells[1].Value;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多