从 DataGridViewSelected Cells c# 制作数据表

Make a datatable from DataGridViewSelected Cells c#

我发现从“选定的行”中获取数据表,但我无法从“选定的单元格”中找到。我需要帮助。

为了解决这个问题,我从选定的单元格中制作了两个列表。这两个列表包含列索引和行索引号,如下所示。有没有办法从这些列表中获取数据表?如果没有,你能给我任何其他解决方案吗?

列索引和行索引列表:

 List<int> cols = dgv.SelectedCells.Cast<DataGridViewCell>().Select(x => x.ColumnIndex).Distinct().ToList();
 List<int> rows = dgv.SelectedCells.Cast<DataGridViewCell>().Select(x => x.RowIndex).Distinct().ToList();

在这里了解或区分索引可能并不重要;

DataGridViewCell 将能够引用 to\of 它是 OwnerColumnOwnerRow,其中不仅包含 Index 属性 而且输入信息和名称。

我将提供一个扩展方法 (GetDataTable),它演示如何生成名为 "SelectedCell"DataTable

它将首先确保将列添加到新的 DataTable 实例中,因为这将定义行使用的字段。在新 DataTable 上创建行时,我们将有条件地迭代初始 cells(始终依赖唯一的列命名)和 SetField.

public static class DataGridViewExtension
{

    public static DataTable GetDataTable(this DataGridViewSelectedCellCollection cellCollection)
    {
        var cells = cellCollection.Cast<DataGridViewCell>()
            .OrderBy(item => item.RowIndex)
            .ThenBy(item => item.ColumnIndex);

        var cellTuples = cells.Select(c => (c.OwningRow, c.OwningColumn, c.Value)).ToArray();
        var distinctColumns = cellTuples.Select(c => c.OwningColumn).Distinct();
        var distinctRows = cellTuples.Select(c => c.OwningRow).Distinct();

        var dt = new DataTable("SelectedCell");

        foreach (var col in distinctColumns)
        {
            // if selected cells are jagged, we may have to add support for, or specify, nullable types of column value type.
            dt.Columns.Add(col.Name, col.ValueType ?? typeof(object));
        }

        foreach (var row in distinctRows)
        {
            var newRow = dt.NewRow();                
            foreach (var (_, OwningColumn, Value) in cellTuples.Where(item => item.OwningRow == row))
            {
                newRow.SetField(OwningColumn.Name, Value);
            }
            dt.Rows.Add(newRow);
        }

        return dt;
    }

    public static IDataReader GetDataReader(this DataGridViewSelectedCellCollection collection)
    {
        var dt = collection.GetDataTable();           
        return new DataTableReader(dt);
    }
}

为了测试,这里是我创建 Form 并添加了 2 个 DataGridView 控件的片段。

public Form1()
{
    dataGridView1.SelectionChanged += DataGridView1_SelectionChanged;
}

private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
    var dt = dataGridView1.SelectedCells.GetDataTable();
    dataGridView2.ClearSelection();
    dataGridView2.DataSource = null;
    dataGridView2.DataSource = dt;
    //var dataReader = dataGridView1.SelectedCells.GetDataReader();
    //var odt = new DataTable("OtherSelectedCells");
    //odt.Load(dataReader);
}

如您所见,需要考虑和处理控制行为,包括:

  • 在单元格控件处于编辑状态时进行选择。
  • 选择不均匀时排序。
  • column\cell 类型处理