2011-03-06 48 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 

不要忘記處理錯誤。