newman
newman

Reputation: 6911

WPF DataGrid: How to clear selection programmatically?

How would one just clear it?

There is UnselectAll or UnselectAllCells methods, but they don't work. Also, setting SelectedItem = null or SelectedIndex = -1 does not work either.

Also I do not want to completely disable the selection, I just want to clear the current selection (if any) and set a new selection programmatically.

Upvotes: 12

Views: 29396

Answers (5)

Ole M
Ole M

Reputation: 347

Are you actually looking to clear selected rows/cells? My understanding was that you wanted to clear the entire DataGrid. If so, you could do this:

myDataGrid.ItemsSource = null;

Upvotes: 0

Evalds Urtans
Evalds Urtans

Reputation: 6694

dataGrid.UnselectAll()

For rows mode

Upvotes: 26

Dunc
Dunc

Reputation: 18922

DataGrid.UnselectAllCells()

It works for me.

Upvotes: 2

Ken Budris
Ken Budris

Reputation: 29

Disabling and reenabling the DataGrid worked for me.

Upvotes: 1

vortexwolf
vortexwolf

Reputation: 14037

To clear current selection, you can use this code (as you see it is different whether the mode is Single or Extended)

if(this.dataGrid1.SelectionUnit != DataGridSelectionUnit.FullRow)
    this.dataGrid1.SelectedCells.Clear();

if (this.dataGrid1.SelectionMode != DataGridSelectionMode.Single) //if the Extended mode
    this.dataGrid1.SelectedItems.Clear();
else 
    this.dataGrid1.SelectedItem = null;

To select new items programmatically, use this code:

if (this.dataGrid1.SelectionMode != DataGridSelectionMode.Single) 
{    //for example, select first and third items
    var firstItem = this.dataGrid1.ItemsSource.OfType<object>().FirstOrDefault();
    var thirdItem = this.dataGrid1.ItemsSource.OfType<object>().Skip(2).FirstOrDefault();

    if(firstItem != null)
        this.dataGrid1.SelectedItems.Add(firstItem);
    if (thirdItem != null)
        this.dataGrid1.SelectedItems.Add(thirdItem);
}
else
    this.dataGrid1.SelectedItem = this.dataGrid1.ItemsSource.OfType<object>().FirstOrDefault(); //the first item

Upvotes: 5

Related Questions