Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 338
newman Avatar asked Oct 07 '10 03:10

newman


4 Answers

DataGrid.UnselectAllCells()

It works for me.

like image 168
Dunc Avatar answered Nov 15 '22 05:11

Dunc


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
like image 30
vortexwolf Avatar answered Nov 15 '22 05:11

vortexwolf


dataGrid.UnselectAll()

For rows mode

like image 25
Evalds Urtans Avatar answered Nov 15 '22 06:11

Evalds Urtans


Disabling and reenabling the DataGrid worked for me.

like image 1
Ken Budris Avatar answered Nov 15 '22 04:11

Ken Budris