【问题标题】:How to get Selected Items in DataGridView as a DataTable?如何将 DataGridView 中的选定项作为 DataTable 获取?
【发布时间】:2010-12-22 22:02:16
【问题描述】:

我有一个从数据库中获取值的 DataGridView。现在我只想打印用户从 UI 中选择的 Selected Items。如果用户想在 DataGridView 中打印出整个表格,这就是我所做的:

var dataTable = dataGridView1.DataSource as DataTable;

现在我正在尝试使用 DataGridView 中的 SelectedCells 属性。还是看不懂:-(

var selecteditems = dataGridView1.SelectedCells as DataTable;

我在这里做错了什么?我想要的只是将我选择的单元格放入一个数据表中。

【问题讨论】:

    标签: c# sql


    【解决方案1】:

    DataGridView.SelectedCells 返回给您的是一个集合,而不是一个 DataTable。

    如果您希望输出为 DataTable,您可以克隆表的结构。然后,遍历 SelectedCells 集合。

    类似:

    DataTable selected = dataTable.Clone();
    for (int i = 0; i < dataGridView.SelectedCells.Count; i++)
    {
         DataRow newRow = selected.NewRow();
         // may have to format below value
         datarow["column"] = dataGridView.SelectedCells[i];
         selected.Rows.Add(newRow);
    }
    

    【讨论】:

      【解决方案2】:

      不应该像这样的倒数第二行:

      newRow["column"] = dataGridView.SelectedCells[i];

      【讨论】:

        猜你喜欢
        • 2012-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多