获得从DataGridView数据表 [英] Get DataTable from DataGridView

查看:143
本文介绍了获得从DataGridView数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形式,是一个CRUD,这种形式可以管理从多个表中的任何数据,如果表有外键的CRUD中的表和列当前表的respectives列,因此在DataGridView可以显示的列为复选框,文本框或组合框

I have one form that is a CRUD, this form can manage any data from many tables, if a table has foreign keys the CRUD found the tables and columns for respectives columns of the current table, so in the DataGridView can show columns as CheckBox, TextBox or ComboBox

我做这一切之前在DataGridView填充有数据,所以我不能用这样的:

I do all this BEFORE the DataGridView is filled with the data, so I can't use this:

dataGridView1.DataSource = dtCurrent;

我需要的是这样的:

I need something like this:

dtCurrent = dataGridView1.DataSource;

但是,只要给一个空

But just give a null

我曾尝试与 ExtensionMethod 到DataGridView:

I have tried with ExtensionMethod to the DataGridView:

public static DataTable ToDataTable(this DataGridView dataGridView, string tableName)
{

    DataGridView dgv = dataGridView;
    DataTable table = new DataTable(tableName);

    // Crea las columnas 
    for (int iCol = 0; iCol < dgv.Columns.Count; iCol++)
    {
        table.Columns.Add(dgv.Columns[iCol].Name);
    }

    /**
      * THIS DOES NOT WORK
      */
    // Agrega las filas 
    /*for (int i = 0; i < dgv.Rows.Count; i++)
    {
        // Obtiene el DataBound de la fila y copia los valores de la fila 
        DataRowView boundRow = (DataRowView)dgv.Rows[i].DataBoundItem;
        var cells = new object[boundRow.Row.ItemArray.Length];
        for (int iCol = 0; iCol < boundRow.Row.ItemArray.Length; iCol++)
        {
            cells[iCol] = boundRow.Row.ItemArray[iCol];
        }

        // Agrega la fila clonada                 
        table.Rows.Add(cells);
    }*/

    /* THIS WORKS BUT... */
    foreach (DataGridViewRow row in dgv.Rows)
    {

        DataRow datarw = table.NewRow();

        for (int iCol = 0; iCol < dgv.Columns.Count; iCol++)
        {
            datarw[iCol] = row.Cells[iCol].Value;
        }

        table.Rows.Add(datarw);
    }

    return table;
} 

我使用的:

dtCurrent = dataGridView1.ToDataTable(dtCurrent.TableName);

在code不工作时:

The code does not works when:

int affectedUpdates = dAdapter.Update(dtCurrent);

我得到重复值的异常(从西班牙语翻译):

I get an Exception about duplicated values (translated from spanish):

申请表的更改没有成功,因为他们将在索引,主键或关系创建重复的值。更改字段或包含重复数据字段中的数据,删除索引,或重新定义索引以允许重复项,然后重试。

我只需要使用更新数据表中的变化在DataGridView

I just need to Update changes in the DataGridView using DataTable

推荐答案

另外,这可能有助于toconvert datagrigview到数据表。

alternatively this may help toconvert datagrigview to datatable.

Dim dt As New DataTable
dt = (DirectCast(DataGridView1.DataSource, DataTable))

做一个直接铸造上的DataGridView的数据表中可以得到最终的结果。

do a direct casting on datagridview for datatable can get the final result.

这篇关于获得从DataGridView数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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