2
votes

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.

1

1 Answers

0
votes

I think you have to capture the size of the column before you start binding the new data-source to it.

with something like this before you bind

List<int> widthsList= new List<int>();
foreach (var column in dataGridView1.Columns)
{
   int ColumnWidth = column.Width;
   widthsList.Add(ColumnWidth);
}

and this after you bind

int j=0;
foreach (int wz in widthsList)
{
   dataGridView1.Columns[j].Width = wz ;
   j++;
}