Refreshing DevExpress.XtraGrid after adding items to list that was boun to it

Dejo picture Dejo · Mar 29, 2012 · Viewed 24.9k times · Source

I have a List<SomeClass> bound to DevExpressXtraGrid like:

MyXtraGrid.DataSource = MyList;

I have some columns made in XtraGrid designer. Everything is ok and rows were shown in grid, but when I add objects to MyList grid is not refreshed and new item was not shown.

I've tried with MyXtraGrid.Refresh(), tried to rebind with MyXtraGrid.DataSource = MyList, but it didn't work.

MyXtraGrix.MyView.PopulareColumns() is not an option, cause I don't wont all fields from MyList to be show in grid, and this will earse columns I've configured with designer.

How to refresh the grid view to show object I've added ?

Answer

Odys picture Odys · Mar 29, 2012

Simply do this:

    private void BindCollection(IEnumerable collection)
    {
        // keep current index
        GridView view = MyXtraGrid.Views[0] as GridView;
        int index = 0;
        int topVisibleIndex = 0;
        if (view != null)
        {
            index = view.FocusedRowHandle;
            topVisibleIndex = view.TopRowIndex;
        }

        MyXtraGrid.BeginUpdate();
        MyXtraGrid.DataSource = collection;
        MyXtraGrid.RefreshDataSource();

        if (view != null)
        {
            view.FocusedRowHandle = index;
            view.TopRowIndex = topVisibleIndex;
        }

        MyXtraGrid.EndUpdate();
    }

You can also get the selected row and reselect it after the new datasource has been set.

Also note that instead of List you can use BindingList<> in order to have the grid to update itself without you having to write a single line of code. Read more here.