How can I sort DataView when I add new item? I have UserControl that contains ListBox control with ItemsSource set to DataView. When I add new item into DataView item is always shown as last in ListBox. What's the best way to sort DataView and show new item in ListBox as sorted?
DataView ListBoxItems = new DataView();
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
DataTable dt = ..."SELECT * FROM table" //populated from database
ListBoxItems = dt.DefaultView;
ListBoxItems.Sort = "Col1 DESC, Col2 ASC";
ListBox.ItemsSource = ListBoxItems;
}
//Adding new item into DataView
DataRowView row = ListBoxItems.AddNew();
row["Col1"] = value1;
row["Col2"] = value2;
ListBoxItems.EndInit();
ListBox.SelectedItem = row;
ListBox.ScrollIntoView(row);
EDIT: I tried solution from link provided by Max Play but without success. Updated code for adding new item:
//Adding new item into DataView
DataRowView row = ListBoxItems.AddNew();
row["Col1"] = value1;
row["Col2"] = value2;
ListBoxItems.EndInit();
ListBox.Items.SortDescriptions.Clear();
ListBox.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription("Col1", System.ComponentModel.ListSortDirection.Descending));
ListBox.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription("Col2", System.ComponentModel.ListSortDirection.Ascending));
ListBox.SelectedItem = row;
ListBox.ScrollIntoView(row);
New item is always shown last in ListBox instead first (based on sorting options).
Found solution, now works as expected.
DataView ListBoxItems = new DataView();
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
DataTable dt = ..."SELECT * FROM table" //populated from database
ListBoxItems = dt.DefaultView;
ListBoxItems.Sort = "Col1 DESC, Col2 ASC";
ListBox.ItemsSource = ListBoxItems;
}
//Adding new item
BindingListCollectionView cv = (BindingListCollectionView)CollectionViewSource.GetDefaultView(ListBox.ItemsSource);
DataRowView row = (DataRowView) cv.AddNew();
row["Col1"] = value1;
row["Col2"] = value2;
cv.CommitNew();
cv.SortDescriptions.Clear();
cv.SortDescriptions.Add(new SortDescription("Col1", ListSortDirection.Descending));
cv.SortDescriptions.Add(new SortDescription("Col2", ListSortDirection.Ascending));
ListBox.SelectedItem = row;
ListBox.ScrollIntoView(row);