I have a Form that shows information about a purchase and within this form I have a DataGridView whose columns are dynamically generated based on a table on the database. This DGV contains information about the items in the selected purchase.
Here's an example of how I generate the columns in runtime in an existing DataGridView:
foreach (ColumnDGV columnDGV in columnsDGV)
{
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.Name = columnDGV.A02_CAMPO;
col.HeaderText = columnDGV.A02_TITULO;
col.DataPropertyName = columnDGV.A02_CAMPO;
this.dataGridView.Columns.Add(col);
}
The object ColumnDGV contains information about the column to be created.
Then I select the columns' names from the columns list and perform the sql query based on those columns:
private void CarregarConteudoDGV()
{
SolicitCompraBLL solicitCompraBLL = new SolicitCompraBLL();
// Gets the columns' names to be used in the SELECT statement.
List<string> columnsNames = this.CamposDGV.Select(c => c.A02_CAMPO).ToList();
// Returns a DataTable containing the items of the selected purchase.
this.dataGridView.DataSource = solicitCompraBLL.ObterItensSolicitacao(columnsNames, this.B11_NUM);
}
When the user clicks in the save button I just iterate through all rows in the DGV and add its values to a nested List where each item is a list of string[2], where the position 0 contains the column name and position 1 its value. Then I pass this List to a method that creates the sql command to update the records.
I can already save the changes of each item in the database, but I also have to insert the added items. How do I know which items should be inserted and which ones should be updated?