C# 如何在DataGridViewRowSelectedRowCollection中获取列

C# 如何在DataGridViewRowSelectedRowCollection中获取列,c#,winforms,datagridviewcolumn,C#,Winforms,Datagridviewcolumn,好了,伙计们,我想这比现在容易多了 public static DataRowCollection ToRows(this DataGridViewSelectedRowCollection Rows) { DataTable table = new DataTable(); foreach (DataColumn column in Rows[0].DataGridView.Columns) { table.Colu

好了,伙计们,我想这比现在容易多了

 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的权限


如何将columns集合强制转换为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();
    }
}
公共静态类DataGridViewExtensions
{
公共静态列表到数据行(此DataGridViewSelectedRowCollection行)
{
如果(行==null | |行.计数==0)
返回null;
返回Rows.Cast()
.Where(x=>x.DataBoundItem是DataRowView)
.Select(x=>((DataRowView)(x.DataBoundItem)).Row.ToList();
}
}

然后从<代码>行> <代码>变量中获取值<代码> DATAROW ,考虑使用这些选项:

  • 行。ItemArray
    包含所有列值
  • 行[索引]
    按索引获取列的值
  • 行[“列名”]
    按列名获取列的值
  • row.Table.Columns
    包含
    DataTable

如果你说
DataGridView
的数据源是什么,为什么需要动态创建这样的数据表,也许可以提出更好的解决方案。如你所见,该方法是静态的,是一个扩展。我有几个网格需要能够获取网格中的选定行,并将这些行返回给调用update方法。我可以在调用方法中这样做,但是每次我想这样做时,我必须复制相同的代码,这意味着每次我在一个地方更新代码,它必须在其他地方更新。所有网格都绑定到数据表吗?目标是从网格中获取选定的数据行吗?是的DataTables,是的selected Row我以后还必须有列,所以这很接近,但不是我要找的。问题是什么?似乎您正试图获取所选数据行,正如您在评论中提到的。使用数据实体删除记录。即使我得到一份名单,这似乎是个问题。目前,帖子根据您的评论回答您的问题,您说是DataTables和Yes Selected Rows。在回答我的问题*时,是否所有网格都绑定到数据表?目标是从网格中获取选定的数据行吗?*但你似乎还有另一个要求。我很想听听你的主要要求(你问这个问题的主要原因),并试着满足它。所以我建议你问一个新的问题来描述你的主要需求,因为目前我坚信这篇文章回答了你的问题。