从DataGridViewSelectedRowCollection复制列的详细信息详细信息、DataGridViewSelectedRowCollection

2023-09-04 04:36:49 作者:殇言

我有这势必会通过一个未知在设计时的SQL查询返回一个DataSet(好吧,我知道查询是一个DataGridView,我只是不知道哪一个用户选择)。

I've got a DataGridView which is bound to a DataSet being returned by an unknown-at-design-time SQL query (well, I know what the queries are, I just don't know which one the user has selected).

我允许用户选择一组从表中的行,打一个OK按钮,然后我想这些行复制到一个新的DataGridView。

I allow the user to select a set of rows from the table and hit an OK button, and I would then like to copy those rows to a new DataGridView.

天真,我用code线沿线的:

Naively, I used code along the lines of:

DataGridView_New.DataSource = DataGridView_Old.SelectedRows

这给了我一些我的新的DataGridView等于行数行的 SelectedRows ,但列不是从SQL查询中的列(因为他们是在 DataGridView_Old );它们是,相反,每一个单独的行(DefaultCellStyle,可调整大小,只读,等)。的的行属性

This gives me a number of rows in my new DataGridView equal to the number of rows in SelectedRows, but the columns are not the columns from the SQL query (as they were in DataGridView_Old); they are, instead, the Row properties of each of the individual rows (DefaultCellStyle, Resizable, ReadOnly, etc.).

有没有快速简便的方法来简单地抓住从 DataGridView_Old 列数据和所选择的行复制到 DataGridView_New

Is there any quick and easy way to simply grab the column data from DataGridView_Old and copy the selected rows into DataGridView_New?

推荐答案

下面是可能会做什么,你需要一个简单的方法:

Here's a simple method that might do what you need:

private void CopySelectedRows(DataGridView sourceDGV, DataGridView destDGV) {
    // Clean up any previous runs.
    destDGV.DataSource = null;
    destDGV.Columns.Clear();

    // Populate the destination DGV with the same columns found in the source DGV.
    foreach (DataGridViewColumn col in sourceDGV.Columns) {
        destDGV.Columns.Add(col.Clone() as DataGridViewColumn);
    }

    // Create a DataTable that has the same structure as the source DGV's DataSource DataTable.
    DataTable table = ((DataTable)sourceDGV.DataSource).Clone();
    // Use the data bound to the selected rows in the source DGV to create rows in your DataTable.
    foreach (DataGridViewRow row in sourceDGV.Rows) {
        if (row.Selected) {
            table.Rows.Add(((DataRowView)row.DataBoundItem).Row.ItemArray);
        }
    }

    destDGV.DataSource = table;
}

我的第一个冲动就是DGV的SelectedRows集合遍历源,但作为用户选择的行,这些都是有序的不一定是一样的显示顺序。

My first impulse was to loop through the source DGV's SelectedRows collection but these are ordered as the user selected the rows, not necessarily the same as the displayed order.

foreach (DataGridViewRow row in sourceDGV.SelectedRows) {
    table.Rows.Add(((DataRowView)row.DataBoundItem).Row.ItemArray);
}
 
精彩推荐
图片推荐