New to Telerik UI for WinForms? Download free 30-day trial

Save and Restore the rows states when resetting.

Environment

Product Version 2018.1 220
Product RadGridView for WinForms

Description

There are cases where you need to reset or rebind the grid which will reset the expanded rows and the position of the scrollbar.

Solution

This article shows how you can save/restore the sates and the scrollbar position.

1. First you need a class to store the state of each row.

struct State
{
    public bool Expanded { get; set; }

    public bool Selected { get; set; }

    public State(bool expanded, bool selected) : this()
    {
        this.Expanded = expanded;
        this.Selected = selected;
    }
}

2. Now you can create the methods that will save and then restore the grid state:

Dictionary<object, State> nodeStates = new Dictionary<object, State>();
private void SaveExpandedStates(GridViewDataRowInfo rowToSave)
{
    if (rowToSave != null && rowToSave.DataBoundItem != null)
    {
        if (!nodeStates.ContainsKey(rowToSave.DataBoundItem))
        {
            nodeStates.Add(rowToSave.DataBoundItem, new State(rowToSave.IsExpanded, rowToSave.IsCurrent));
        }
        else
        {
            nodeStates[rowToSave.DataBoundItem] = new State(rowToSave.IsExpanded, rowToSave.IsCurrent);
        }
    }
    foreach (GridViewDataRowInfo childRow in rowToSave.ChildRows)
    {
        SaveExpandedStates(childRow);
    }
}

private void RestoreExpandedStates(GridViewDataRowInfo rowToRestore)
{
    if (rowToRestore != null && rowToRestore.DataBoundItem != null &&
        nodeStates.ContainsKey(rowToRestore.DataBoundItem))
    {
        rowToRestore.IsExpanded = nodeStates[rowToRestore.DataBoundItem].Expanded;
        rowToRestore.IsCurrent = nodeStates[rowToRestore.DataBoundItem].Selected;
        rowToRestore.IsSelected = nodeStates[rowToRestore.DataBoundItem].Selected;
    }

    foreach (GridViewDataRowInfo childRow in rowToRestore.ChildRows)
    {
        RestoreExpandedStates(childRow);
    }
}

3. The final step is to use the above methods, this snippet show how restore the scrollbar position as well:

private void RadButton1_Click(object sender, EventArgs e)
{
    int scrollBarValue = radGridView1.TableElement.VScrollBar.Value;
    foreach (GridViewDataRowInfo rowToSave in radGridView1.Rows)
    {
        SaveExpandedStates(rowToSave);
    }


    radGridView1.DataSource = null;
    radGridView1.DataSource = master;


    foreach (GridViewDataRowInfo rowToRestore in radGridView1.Rows)
    {
        RestoreExpandedStates(rowToRestore);
    }

    radGridView1.TableElement.VScrollBar.Value = scrollBarValue;

}
In this article