I have one form that is CRUD, this form can manage any data from many tables, if the table has foreign keys, CRUD detected tables and columns for respect columns of the current table, so columns like CheckBox, TextBox or ComboBox can be displayed in DataGridView
I do all this before the DataGridView is populated with data, so I cannot use this:
dataGridView1.DataSource = dtCurrent;
I need something like this:
dtCurrent = dataGridView1.DataSource;
But just give null
I tried using ExtensionMethod in a DataGridView:
public static DataTable ToDataTable(this DataGridView dataGridView, string tableName)
{
DataGridView dgv = dataGridView;
DataTable table = new DataTable(tableName);
for (int iCol = 0; iCol < dgv.Columns.Count; iCol++)
{
table.Columns.Add(dgv.Columns[iCol].Name);
}
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;
}
I use:
dtCurrent = dataGridView1.ToDataTable(dtCurrent.TableName);
The code does not work if:
int affectedUpdates = dAdapter.Update(dtCurrent);
I get the Duplicate Values Exception (Spanish translation):
, , , , . , , , .
DataGridView DataTable