2011-03-06 85 views
4

我有一种形式是一个CRUD,这种形式可以管理来自多个表的任何数据,如果一个表有外键CRUD找到当前表的各个列的表和列,那么在DataGridView中可以显示为复选框,文本框或组合框列从DataGridView获取DataTable

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

dataGridView1.DataSource = dtCurrent; 

我需要的是这样的:

dtCurrent = dataGridView1.DataSource; 

但只给一个空

我与ExtensionMethod试图在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); 

代码不工作时:

int affectedUpdates = dAdapter.Update(dtCurrent); 

我收到一个异常关于重复值(从西班牙语翻译):

对表请求的更改不成功,因为它们会在索引,主键或关系中创建重复值。更改包含重复数据的字段或字段中的数据,删除索引或重新定义索引以允许重复条目,然后重试。

我只需要使用数据表

回答

5

更新DataGridView的变化或者这可能有助于toconvert datagrigview到数据表。

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

对datatable做datagridview的直接转换就可以得到最终结果。

+1

类似于上面的'DataTable dataTable =(DataTable)dataGridView1.DataSource;'为我工作。 另请参阅:http://stackoverflow.com/questions/6295161/how-to-build-a-datatable-from-a-datagridview – surfmuggle 2013-02-13 21:48:07

+0

你读过这个问题吗?在c#请 – 2017-01-09 10:52:40

-2

这个怎么样:

DataView dv = (DataView)(dataGridView1.DataSource); 

dt = dv.ToTable(); 

适用于所有的情况下!

+3

不要害怕留下评论/原因时downvoting ... – 2014-09-04 18:37:16

+2

你不能将DataTable转换为DataView。只需使用DataTable dt =(DataTable)(dataGridView1.DataSource);直接,不需要转换到DataView。 – randomizer 2014-09-11 07:08:30

2

如果需要实际的数据表源的基准,试试这个

((DataRowView)DataGridView1.Rows[0].DataBoundItem).DataView.Table 

不要忘记处理错误。