Freigeben über


Silverlight Datagrid add/delete operations and ObservableCollection

In my previous post,the collection I used is a List. So, each time I add a new item to the list, the itemsource of the datagrid need to be modified/reset to reflect the latest changes to the collection.

Using the ObservableCollection gets this functionality comes free of cost/extra code for us. The observable collection implements InotifyCollectioChanged which notifies the underlying control whenever anything has changed in the list.

Here is the page.xaml snippet

Here is the page.xaml.cs snippet

    public partial class Page : UserControl

    {

        ObservableCollection<Customer> clist = new ObservableCollection<Customer>();

      public Page()

        {

            InitializeComponent();

            int count = 25;

            for (int i = 0; i < count; i++)

            {

                Customer cust1 = new Customer("custfname" + i, "custlastname" + i, i, "address" + i, "city" + i, "country" + i);

                clist.Add(cust1);

            }

            dg.ItemsSource = clist;

        }

        private void addbutton_Click(object sender, RoutedEventArgs e)

        {

            int count = clist.Count;

            Customer cust1 = new Customer("custfname" + count, "custlastname" + count, count, "address" + count, "city" + count, "country" + count);

            clist.Add(cust1);

            dg.ScrollIntoView(clist[clist.Count-1], dg.Columns[5]);

        }

        private void deletebutton_Click(object sender, RoutedEventArgs e)

        {

            int deleteIndex = clist.Count - 1;

            clist.RemoveAt(deleteIndex);

            dg.ScrollIntoView(clist[clist.Count - 1], dg.Columns[5]);

        }

    }}

Thus, using the ObservableCollection helps us view in datagrid without any writing extra code the changes made to the underlying collection.

More about Silverlight ObservableCollection at https://msdn.microsoft.com/en-us/library/ms668604(VS.95).aspx

Comments