我有一个CRUD表单,可以管理许多表中的任何数据。如果表中有外键,CRUD会找到相应列的表和列名。因此,在DataGridView中可以显示列为复选框、文本框或组合框。
在填充数据之前,我完成了所有这些操作,所以我不能使用以下内容:
dataGridView1.DataSource = dtCurrent;
我需要类似这样的东西:
dtCurrent = dataGridView1.DataSource;
但只需提供一个空值
我尝试使用扩展方法来操作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中的更改。