【问题标题】:Get DataTable from DataGridView从 DataGridView 获取 DataTable
【发布时间】:2011-03-06 01:52:41
【问题描述】:

我有一个 CRUD 表单,这个表单可以管理来自许多表的任何数据,如果一个表有外键,那么 CRUD 会为当前表的各个列找到表和列,所以在 DataGridView 中可以显示列作为 CheckBox、TextBox 或 ComboBox

我在 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);

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

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

我只需要使用 DataTable 更新 DataGridView 中的更改

【问题讨论】:

    标签: c# .net winforms datagridview


    【解决方案1】:

    或者,这可能有助于将 datagrigview 转换为数据表。

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

    直接在datagridview上对datatable进行强制转换就可以得到最终结果。

    【讨论】:

    • 类似于上述DataTable dataTable = (DataTable) dataGridView1.DataSource; 为我工作。另见:stackoverflow.com/questions/6295161/…
    • 在 C# 中,var dt = new DataTable(); dt = (DataTable)DataGridView1.DataSource;
    【解决方案2】:

    如果您需要对实际 DataTable 源的引用,试试这个

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

    不要忘记处理错误。

    【讨论】:

      【解决方案3】:

      我是这样写的:

      private DataTable GetDataGridViewAsDataTable(DataGridView _DataGridView) 
      {
          try {
              if (_DataGridView.ColumnCount == 0) return null;
              DataTable dtSource = new DataTable();
              //////create columns
              foreach(DataGridViewColumn col in _DataGridView.Columns) {
                  if (col.ValueType == null) dtSource.Columns.Add(col.Name, typeof(string));
                  else dtSource.Columns.Add(col.Name, col.ValueType);
                  dtSource.Columns[col.Name].Caption = col.HeaderText;
              }
              ///////insert row data
              foreach(DataGridViewRow row in _DataGridView.Rows) {
                  DataRow drNewRow = dtSource.NewRow();
                  foreach(DataColumn col in dtSource.Columns) {
                      drNewRow[col.ColumnName] = row.Cells[col.ColumnName].Value;
                  }
                  dtSource.Rows.Add(drNewRow);
              }
              return dtSource;
          }
          catch {
              return null;
          }
      }
      

      【讨论】:

        【解决方案4】:
         DataTable dt = new DataTable();
            dt = ((DataTable)DataGridView1.DataSource);
        

        【讨论】:

        • 点评来源: 您好,请不要只回答源代码。尝试对您的解决方案如何工作提供一个很好的描述。见:How do I write a good answer?。谢谢
        【解决方案5】:

        这个呢:

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

        适用于所有情况!

        【讨论】:

        • 您无法将 DataTable 转换为 DataView。只需使用 DataTable dt = (DataTable)(dataGridView1.DataSource);直接,无需转换为 DataView。
        猜你喜欢
        • 1970-01-01
        • 2022-09-23
        • 1970-01-01
        • 2012-03-20
        • 1970-01-01
        • 2011-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多