Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select first/previous/next/last row in wpf DataGrid

Tags:

wpf

datagrid

I've got a WPF application which contains a standard DataGrid showing a lot of data.

Now I want to add buttons to select the next/first/previous/last row.

Is there a way to tell the DataGrid to change the selection for me?

I tried to use

private void SelectNext_Click(object sender, RoutedEventArgs e)
{
  datagrid.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}

but it does not work for me (does not change the selected item, sets just the cell focus to the first item instead).

like image 396
Sam Avatar asked Dec 15 '22 22:12

Sam


2 Answers

private void SelectNext_Click(object sender, RoutedEventArgs e)
{
   if (dataGrid.Items.Count - 1 > datagrid.SelectedIndex)
   {
      datagrid.SelectedIndex++;
   }
}

private void SelectPrevious_Click(object sender, RoutedEventArgs e)
{
   if (dataGrid.SelectedIndex > 0)
   {
      datagrid.SelectedIndex--;
   }
}

private void SelectFirst_Click(object sender, RoutedEventArgs e)
{
   dataGrid.SelectedIndex = 0;
}

private void SelectLast_Click(object sender, RoutedEventArgs e)
{
   dataGrid.SelectedIndex = dataGrid.Items.Count - 1;
}
like image 142
Dean Chalk Avatar answered Dec 28 '22 09:12

Dean Chalk


If you fill your datagrid with a datasource by databinding, you can do that

Example of button "next"

private void btnNext_Click(object sender, RoutedEventArgs e)
{
        ICollectionView view = CollectionViewSource.GetDefaultView(yourDataSource);
        view.MoveCurrentToNext();
}

The interface ICollectionView has all the methods you need for moving the current item

In XAML remember also to set

<DataGrid .....     IsSynchronizedWithCurrentItem="True" >
like image 25
Klaus78 Avatar answered Dec 28 '22 08:12

Klaus78