DataGridView 选择的行到 DataTable [英] DataGridView selected rows to DataTable

查看:42
本文介绍了DataGridView 选择的行到 DataTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试仅将 DataGridView 的选定行添加到 DataTable,即使未选择该行,我使用的代码也始终从第一行开始......有人知道如何请解决这个问题?

I'm trying to add only the selected rows of a DataGridView to a DataTable, the code that I'm using always start from the first row even if this one is not selected... Does someone have an idea for how to fix this please?

 DataTable dt = new DataTable("Rapport");

            //Generating columns to datatable:
            foreach (DataGridViewColumn column in dataGridView1.Columns)
                dt.Columns.Add(column.Name, typeof(string));

            //Adding selected rows of DGV to DataTable:
            for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
            {
                dt.Rows.Add();
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    dt.Rows[i][j] = dataGridView1[j, i].Value;
                }
            }

推荐答案

您必须像访问 SelectedRows 一样

dt.Rows[i][j] = dataGridView1.SelectedRows[i].Cells[j].Value;

如果您的 DataTable 与 Cell 的类型相同,则更好

Also its better if your DataTable has the same type as of Cell

DataTable dt = new DataTable();
 foreach (DataGridViewColumn column in dataGridView1.Columns)
    dt.Columns.Add(column.Name, column.CellType); //better to have cell type

所以你的代码是:

DataTable dt = new DataTable();
foreach (DataGridViewColumn column in dataGridView1.Columns)
    dt.Columns.Add(column.Name, column.CellType); //better to have cell type
for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
{
     dt.Rows.Add();
     for (int j = 0; j < dataGridView1.Columns.Count; j++)
     {
         dt.Rows[i][j] = dataGridView1.SelectedRows[i].Cells[j].Value;
                                   //^^^^^^^^^^^
     }
 }

这篇关于DataGridView 选择的行到 DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆