New to Telerik UI for WinFormsStart a free 30-day trial

Binding to ObservableCollection

Updated over 6 months ago

The example bellow demonstrates how to bind RadGridView to an ObservableCollection. This collection represents a dynamic data collection that provides notification when changes (add, move, remove) occur.

This collection is available in .NET version 4.0 and above. For this reason it is only supported in the .NET4.0 version of our assemblies (the ones with suffix .40), so please make sure to use those in order to take advantage of this functionality.

The example creates an ObservableCollection of Person, initializes the collection and assigns it to the grid's DataSource property. There are also three buttons allowing the user to add, remove and move items from and in the collection. The changes in the collection are automatically reflected by the grid.

![WinForms RadGridView Binding to ObservableCollection](images/gridview-populating-with-data-binding-to- observable-collection001.png)

1. First place a RadGridView and 3 buttons on a blank form. Name the buttons accordingly:

![WinForms RadGridView Create Structure](images/gridview-populating-with-data-binding-to- observable-collection002.png)

2. Add the following sample class to the project:

C#
  
public class Person
{
    public string FirstName { get; set; }
    
    public string LastName { get; set; }
    
    public int Age { get; set; }
    
    public Person(string firstName, string lastName, int age)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Age = age;
    }
}

3. Define the collection along with the function that initializes it:

C#
private  System.Collections.ObjectModel.ObservableCollection<Person> people = new  System.Collections.ObjectModel.ObservableCollection<Person>();
private void IntilalizeCollection()
{
    people.Add(new Person("Johnathan", "Gartner", 45));
    people.Add(new Person("Jeannine", "Richart", 25));
    people.Add(new Person("Merry", "Sparacino", 15));
    people.Add(new Person("Sandi", "Willman", 32));
    people.Add(new Person("Damion", "Dagley", 51));
}

4. Add the following event handlers for the buttons:

C#
private void Add_Click(object sender, EventArgs e)
{
    people.Add(new Person("Damion", "Dagley", 51));
}
C#
private void Remove_Click(object sender, EventArgs e)
{
    if (people.Count > 0)
    {
        people.RemoveAt(0);
    }
}
C#
private void Move_Click(object sender, EventArgs e)
{
    people.Move(people.Count - 1, 0);
}

5. Finally just call the InitializeCollection method to populate the collection and bind the RadGridView to it

C#
private void BindingToObservableCollection_Load(object sender, EventArgs e)
{
    IntilalizeCollection();
    this.radGridView1.DataSource = people;
}

Now each change you introduce to the collection by pressing the buttons will be automatically reflected in RadGridView.

See Also

In this article
See Also
Not finding the help you need?
Contact Support