好的,伙计们,我认为这会比实际更容易。
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/