0
votes

In one of my C# Winform, I have a DataGridView that I update when the user presses a refresh button.

The problem is that the selected row is lost in the process.

I would like to be able to do the following:

private void function Refresh()
{
UpdateBegin(); // Keep the selected row in memory
Update();
UpdateEnd(); // Apply the selected row to the DataGridView
}

Here is the Update function. It updates the data source, clears all the columns and bring back those that are required with the proper header text:

private void Update()
{
    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;
    }

}

However, the selected rows property of my DataGridView is Read-only.

Is there a workaround to this ?

1
Could you tell us more about what your Update does? Does it clear all the rows, then pull the latest from a database somewhere? The reason I ask is, you should be able to add and remove rows without altering the selection, unless you remove part of the selection. In that case, I believe the selection is only altered by what you removed. - B L
The Update function gets and updated data source, clears the dataGrid and brings back the required column. - Francis.Beauchamp

1 Answers

0
votes

Did you try something like the following excerpt from MSDN (link) on this topic:

void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    this.dataGridView1.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
    this.dataGridView1.Rows[e.RowIndex].Selected = true;
}

Second line in this code snippet shows how to programmatically select the row, provided that you keep track of the selected RowIndex (as it's probably done in your UpdateBegin() function call).

Hope this could help.