c# - 将选定的行从数据 GridView 传输到另一个数据 GridView

标签 c# datagridview

我的问题是将选定的行从数据 GridView 传输到另一个数据 GridView 。如果我使用主键并将值从数据库获取到另一个数据库,或者将所选行的数据从 datagridview1 发送到 datagridview2,我不知道该使用什么

最佳答案

您可以创建一个新的 DataTable 并将所有选定的行插入到该 DataTable

DataTable GetSelectedRows(DataGridView dgv)
{
    var dt = new DataTable();
    foreach (DataGridViewColumn column in dgv.Columns)
    {
        if (column.Visible)
        {
            // You could potentially name the column based on the DGV column name (beware of dupes)
            // or assign a type based on the data type of the data bound to this DGV column.
            dt.Columns.Add();
        }
    }

    object[] cellValues = new object[dgv.Columns.Count];
    foreach (DataGridViewRow row in dgv.Rows)
    {
        if (!row.Selected) continue; // Add only Selected Rows

        for (int i = 0; i < row.Cells.Count; i++)
            cellValues[i] = row.Cells[i].Value;

        dt.Rows.Add(cellValues);
    }

    return dt;
}

您可以使用此方法将所有 SelectedRow 传递给新的 DataGridView

dataGridView2.DataSource = GetSelectedRows(dataGridView1)

关于c# - 将选定的行从数据 GridView 传输到另一个数据 GridView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32033199/

相关文章:

c# - 如何在 c# 中动态显示 datagridview 列中的数字计时器(秒表)?

c# - 使用 C# 和 ASP.NET 将数据从 Excel 文件导出到 SQL Server 表的最佳方法?

database - DatagridView 未从 DataTable 加载

c# - 为什么我们需要在 C# 中类型转换枚举

c# - 如何压缩大文件 C#

c# - 通过在 datagridviewcolum 中指定 DefaultCellStyle.Format 值来显示百分比

c# - 如何刷新DataGridView单元格样式

javascript - 如何为网格中的字段调用 javascript 函数

c# - 为什么我的堆栈跟踪缺少步骤?

c# - 添加更多我的用户控件容器或用户控件集合显示