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

查看:345
本文介绍了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 具有相同类型的单元格

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天全站免登陆