I have a problem please help me:
I have a datagrid in WPF named contacts_datagrid. It load data from a CSV file with 2 fields (Name, phone Number). Upon running my app it loads data from this csv file. I have put an import function which imports another csv file and appends its data to the buttom of the first csv file using this code:
foreach (DataRow drow in second_csv_file.Rows)
{
First_csv_file.Rows.Add(drow.ItemArray);
}
It works fine. Then I want to sort my column alphabetically and I use this:
ICollectionView dataView = CollectionViewSource.GetDefaultView(contacts_datagrid.ItemsSource);
dataView.SortDescriptions.Clear();
dataView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
dataView.Refresh();
this works fine either and after doing this my new table has all merged data in ascending format. The problem is after doing this when I try to delete a row for a selected index using:
table.Rows.RemoveAt(contacts_datagrid.SelectedIndex);
the program dos not delete the right index. For example my first csv is [a,c,c,d] and the second csv is [z,a,d,k] after sorting the table contains and shows [a,a,c,c,d,d,k,z] which I want but when I click on row “z” it does not remove “z” row and instead it removes “k”. in other words the index is the same but the positions of rows has been changed, the delete function now removes based on last indexes before it was sorted. I have tried refreshing datagrid and also reloading datagrid but no success, please help me thanks.
The SelectedIndex in your DataGrid will not point to the same item as the index in the source after doing sort operations on the grid.
Try using SelectedItem instead and Remove(item) instead of RemoveAt(index).