I want to refresh the content of a DataGridView in C# Winform and keep its visual appearance.
The only way I could do a refresh is with this function which re-initialise the grid:
It updates the data source, clears all the columns and bring back those that are required with the proper header text.
private void InitDataGrid()
{
allItem = DataRepository.LotProvider.GetByIdProduit(detail.IdProduit)
dataGridView1.DataSource = allItem;
dataGridView1.Columns.Clear();
// Get a dictionary of the required column ID / shown text
Dictionary<string, string> dictionary = InitDisplayedFields();
foreach (KeyValuePair<string, string> column in dictionary)
// If the grid does not contain the key
if (!dataGridView1.Columns.Contains(column.Key))
{
// Add the column (key-value)
int id = dataGridView1.Columns.Add(column.Key, column.Value);
// Bind the property
dataGridView1.Columns[id].DataPropertyName = column.Key;
}
}
The problem is that if the user stretches a column from Y size to X size and refresh the DataGridView, the column will go back to Y size.
I could not go around the Clear() because otherwise, the grid shows all the datasource columns when initialised.
What I want is to keep the X size of every stretched columns.
I would appreciate any suggestion in order to optimise the current code.