How Do I unselect a WPF datagrid row if already selected?

Boom Ba 166 Reputation points
2022-03-30T01:09:26.937+00:00

In my datagrid the DataGridTextColumn are binded to a database columns & I have the following properties and events set

SelectionMode="Single"
SelectionUnit="FullRow"
SelectionChanged="dataGrid1_SelectionChanged"

Where

 void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
 DataGrid grid = (DataGrid)sender;
 dynamic selected_row = grid.SelectedItem;

 EmpID.Text = selected_row["EmpID"].ToString();
 FullName.Text = selected_row["FullName"].ToString();
 Age.Text = FormattedDate(selected_row["Age"].ToString());
 DOJ.Text = selected_row["DOJ"].ToString();
 }

EmpID, FullName, ... on the left side of the above code are just textboxes.

How do I unselect the selected row when I click it or use Ctrl+Click to unselect whichever is easier/better ?

When I hit the Ctrl+Click on a selected row right now I get the error Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference

Developer technologies | Windows Presentation Foundation
Developer technologies | XAML
Developer technologies | C#
{count} votes

Accepted answer
  1. Hui Liu-MSFT 48,676 Reputation points Microsoft External Staff
    2022-03-30T07:16:48.943+00:00

    MainWindow.xaml:

    <Window.DataContext>  
            <local:ViewModel/>  
        </Window.DataContext>  
        <Grid>  
            <Grid.RowDefinitions>  
                <RowDefinition/>  
                <RowDefinition/>  
            </Grid.RowDefinitions>  
            <DataGrid x:Name="dg" Height="260" Width="290"  ItemsSource="{Binding Items}"  SelectionMode="Single"   
                      AutoGenerateColumns="False"    SelectionUnit="FullRow"  SelectionChanged="dg_SelectionChanged" >  
                <DataGrid.Resources>  
                    <Style TargetType="{x:Type DataGridCell}">  
                        <EventSetter Event="PreviewMouseLeftButtonDown" Handler="DoSelectedRow"/>  
                    </Style>  
                </DataGrid.Resources>  
                <DataGrid.Columns>  
                    <DataGridTextColumn x:Name="ID" Header="ID" Binding="{Binding ID}"/>  
                    <DataGridTextColumn x:Name="FullName" Header="FullName" Binding="{Binding FullName}"/>  
                    <DataGridTextColumn x:Name="Description" Header="Description" Binding="{Binding Description}"/>  
                </DataGrid.Columns>  
            </DataGrid>  
            <StackPanel Grid.Row="1">  
                <TextBox x:Name="ImID" Width="100" Height="40"/>  
                <TextBox x:Name="ImFullName" Width="100" Height="40"/>  
                <TextBox x:Name="ImDescription" Width="100" Height="40"/>  
            </StackPanel>  
        </Grid>  
    

    MainWindow.xaml.cs:

    using System.Collections.ObjectModel;  
    using System.ComponentModel;  
    using System.Windows;  
    using System.Windows.Controls;  
    using System.Windows.Input;  
    using System.Windows.Media;  
      
    namespace DataGridSelected  
    {  
      public partial class MainWindow : Window  
      {  
        public MainWindow()  
        {  
          InitializeComponent();  
        }  
        private void dg_SelectionChanged(object sender, SelectionChangedEventArgs e)  
        {  
          DataGrid grid = (DataGrid)sender;  
          dynamic selected_row = grid.SelectedItem;  
          //ImID.Text= selected_row["ID"].ToString();  
        }  
        public void DoSelectedRow(object sender, MouseButtonEventArgs e)  
        {  
          DataGridCell cell = sender as DataGridCell;  
          if (cell != null && !cell.IsEditing)  
          {  
            DataGridRow row = FindVisualParent<DataGridRow>(cell);  
            if (row != null)  
            {  
              row.IsSelected = !row.IsSelected;  
              e.Handled = true;  
            }  
          }  
        }  
        public static Parent FindVisualParent<Parent>(DependencyObject child)   where Parent : DependencyObject  
        {  
          DependencyObject parentObject = child;  
      
          while (!((parentObject is System.Windows.Media.Visual)  
                  || (parentObject is System.Windows.Media.Media3D.Visual3D)))  
          {  
            if (parentObject is Parent || parentObject == null)  
            {  
              return parentObject as Parent;  
            }  
            else  
            {  
              parentObject = (parentObject as FrameworkContentElement).Parent;  
            }  
          }  
          parentObject = VisualTreeHelper.GetParent(parentObject);  
          if (parentObject is Parent || parentObject == null)  
          {  
            return parentObject as Parent;  
          }  
          else  
          {  
            return FindVisualParent<Parent>(parentObject);  
          }  
        }  
      }  
      public class ViewModel : INotifyPropertyChanged  
      {  
        private int _selectedIndex = 0;  
        public int SelectedIndex  
        {  
          get { return _selectedIndex; }  
          set { _selectedIndex = value; OnPropertyChanged("SelectedIndex"); }  
        }  
      
        private ObservableCollection<Item> items = new ObservableCollection<Item>();  
        public ObservableCollection<Item> Items  
        {  
          get { return items; }  
          set { items = value; }  
        }  
        public ViewModel()  
        {  
          Items.Add(new Item() { ID="1", FullName="image1",  Description = "image1" });  
          Items.Add(new Item() { ID = "2", FullName = "image2",  Description = "image2" });  
          Items.Add(new Item() { ID = "3", FullName = "image3", Description = "image3" });  
          Items.Add(new Item() { ID = "4", FullName = "image4", Description = "image4" });  
        }  
        public event PropertyChangedEventHandler PropertyChanged;  
        private void OnPropertyChanged(string propertyName)  
        {  
          if (this.PropertyChanged != null)  
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));  
        }  
      }  
      public class Item : INotifyPropertyChanged  
      {  
        private string id;  
        public string ID  
        {  
          get { return id; }  
          set { id = value; OnPropertyChanged("ID"); }  
        }  
        private string fullName;  
        public string FullName  
        {  
          get { return fullName; }  
          set { fullName = value; OnPropertyChanged("FullName"); }  
        }  
        private string description;  
        public string Description  
        {  
          get { return description; }  
          set { description = value; OnPropertyChanged("Description"); }  
        }  
        public event PropertyChangedEventHandler PropertyChanged;  
        private void OnPropertyChanged(string propertyName)  
        {  
          if (this.PropertyChanged != null)  
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));  
        }  
      }  
    }  
    

    The result:
    188256-22.gif

    Update:

    <Grid>  
            <Grid.RowDefinitions>  
                <RowDefinition/>  
                <RowDefinition/>  
            </Grid.RowDefinitions>  
            <DataGrid x:Name="dg" Height="260" Width="290"  SelectionMode="Single"  AutoGenerateColumns="False"   
                        SelectionUnit="FullRow"   SelectionChanged="dg_SelectionChanged" >  
                <DataGrid.Resources>  
                    <Style TargetType="{x:Type DataGridCell}">  
                        <EventSetter Event="PreviewMouseLeftButtonDown" Handler="DoSelectedRow"/>  
                    </Style>  
                </DataGrid.Resources>  
                <DataGrid.Columns>  
                    <DataGridTextColumn x:Name="ID" Header="ID" Binding="{Binding Id}"/>  
                    <DataGridTextColumn x:Name="FullName" Header="FullName" Binding="{Binding FullName}"/>  
                    <DataGridTextColumn x:Name="Description" Header="Description" Binding="{Binding Description}"/>  
                </DataGrid.Columns>  
            </DataGrid>  
            <TextBox x:Name="ImID" Grid.Row="1"  Width="100" Height="50" />  
        </Grid>  
    

    MainWindow.xaml.cs:

    using System.Collections.Generic;  
    using System.Data;  
    using System.Data.SqlClient;  
    using System.Linq;  
    using System.Windows;  
    using System.Windows.Controls;  
    using System.Windows.Input;  
    using System.Windows.Media;  
      
    namespace DataGridSelected  
    {  
      public partial class MainWindow : Window  
      {  
        public MainWindow()  
        {  
          InitializeComponent();  
          FillGrid();  
        }  
        private void FillGrid()  
        {  
          string constr = @"constr";  
      
          SqlConnection con = new SqlConnection(constr);  
          con.Open();  
          SqlCommand cmd = new SqlCommand("Select * From [dbo].[Table]", con);  
          SqlDataAdapter da = new SqlDataAdapter(cmd);  
          var dt = new DataTable();  
          da.Fill(dt);  
          dg.ItemsSource = dt.DefaultView;  
          List<int> SelectedIndexs = dg.SelectedItems  
            .Cast<DataRowView>()  
            .Select(view => dt.Rows.IndexOf(view.Row))  
            .ToList();  
          con.Close();  
        }  
            private void dg_SelectionChanged(object sender, SelectionChangedEventArgs e)  
            {  
               DataGrid grid = (DataGrid)sender;  
               dynamic selected_row = grid.SelectedItem;  
                if (selected_row == null)  
                {  
                    ImID.Text = "";  
                }  
                else  
                {  
                    ImID.Text = selected_row["ID"].ToString();  
                }  
                 
            }  
            public void DoSelectedRow(object sender, MouseButtonEventArgs e)  
        {  
          DataGridCell cell = sender as DataGridCell;  
          if (cell != null && !cell.IsEditing)  
          {  
            DataGridRow row = FindVisualParent<DataGridRow>(cell);  
            if (row != null)  
            {  
              row.IsSelected = !row.IsSelected;  
                     
              e.Handled = true;  
            }  
          }  
        }  
        public static Parent FindVisualParent<Parent>(DependencyObject child)   where Parent : DependencyObject  
        {  
          DependencyObject parentObject = child;  
      
          while (!((parentObject is System.Windows.Media.Visual)  
                  || (parentObject is System.Windows.Media.Media3D.Visual3D)))  
          {  
            if (parentObject is Parent || parentObject == null)  
            {  
              return parentObject as Parent;  
            }  
            else  
            {  
              parentObject = (parentObject as FrameworkContentElement).Parent;  
            }  
          }  
          parentObject = VisualTreeHelper.GetParent(parentObject);  
          if (parentObject is Parent || parentObject == null)  
          {  
            return parentObject as Parent;  
          }  
          else  
          {  
            return FindVisualParent<Parent>(parentObject);  
          }  
        }  
      }  
    }  
    

    The result:
    selected item 4:
    188899-image.png
    unselected item 4:
    189025-image.png


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.