c# - 如何获取 DataGridViewRowSelectedRowCollection 中的列

标签 c# winforms datagridviewcolumn

好的,伙计们,我认为这会比实际更容易。

 public static DataRowCollection ToRows(this DataGridViewSelectedRowCollection Rows)
 {
     DataTable table = new DataTable();            

     foreach (DataColumn column in Rows[0].DataGridView.Columns)
     {
         table.Columns.Add(column);
     }

     foreach (DataGridViewRow row in Rows)
     {
         DataRow newRow = ((DataRowView)row.DataBoundItem).Row;
         table.ImportRow(newRow);
     }

     return table.Rows;
}

我正在尝试获取 DataGridViewSelectedRowCollection 中一行的列。上面的代码在 table.Columns.Add(column) 上引发 InvalidCast 错误,因为它试图将 DataGridViewColumns 转换为 DataTable 列。我无权访问 DataGridView,因为我在一个扩展 DataGridViewSelectedRowCollection 的静态方法中并且无权访问 DataGridView。

如何将列集合转换为 DataColumns 对象?

最佳答案

您可以创建一个扩展方法,以这种方式返回所选网格行后面的数据行:

public static class DataGridViewExtensions
{
    public static List<DataRow> ToDataRows(this DataGridViewSelectedRowCollection Rows)
    {
        if (Rows == null || Rows.Count == 0)
            return null;

        return Rows.Cast<DataGridViewRow>()
                   .Where(x => x.DataBoundItem is DataRowView)
                   .Select(x => ((DataRowView)(x.DataBoundItem)).Row).ToList();
    }
}

然后要从 DataRow 类型的 row 变量中获取值,请考虑使用这些选项:

  • row.ItemArray 包含所有列值
  • row[index] 通过索引获取列的值
  • row["column name"]通过列名获取列的值
  • row.Table.Columns 包含 DataTable
  • 的列列表

关于c# - 如何获取 DataGridViewRowSelectedRowCollection 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38354084/

相关文章:

c# - 如何在 C# 中创建多维数组列表?

c# - 如何绑定(bind)到 .NET 中的编程属性?

c# - 调用MySql Table时自定义DataGridview宽度

c# - DataGridView:查找 ColumnHeaders 是否真的可见

c# - db4o 如何通过配置重命名类

c# - 如何在 .net windows 窗体应用程序中将访问控制与我的 ORM 集成?

c# - 如何对任务并行性进行单元测试

c# - 如何使用 RichTextBox 显示 html 内容?

.net - WM_DESTROY、WM_CLOSE绕过IMessageFilter

c# - 在 C# 中的 DataGridView 中创建列