【发布时间】: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