【问题标题】:Transfering selected rows from data grid view to another data grid view将选定的行从 datagridview 传输到另一个数据网格视图
【发布时间】:2015-08-16 08:29:27
【问题描述】:

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

【问题讨论】:

    标签: c# datagridview


    【解决方案1】:

    您可以创建一个新的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;
    }
    

    您可以使用此将所有 SelectedRows 传递给新的 DataGridView

    dataGridView2.DataSource = GetSelectedRows(dataGridView1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 1970-01-01
      相关资源
      最近更新 更多