Search code examples
c#wpfdata-bindingwpfdatagrid

When i double click on WPF DataGrid row for get cell value, return NULL


I get this error in my code in MouseDoubleClick event.

Error: System.NullReferenceException: 'Object reference not set to an instance of an object.'

<DataGrid x:Name="dtgTarafDovvom" Style="{StaticResource DataGridStyle1}" ItemsSource="{Binding}" MouseDoubleClick="dtgTarafAvval_MouseDoubleClick">
  <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Path=TarafeynQarardadID}" Header="کد ">
    </DataGridTextColumn>
</DataGrid>

here is my c# code

private void dtgTarafAvval_MouseDoubleClick(object sender, ouseButtonEventArgs e) {
  TarafeynQarardadDTO t = dtgTarafAvval.SelectedItem as TarafeynQarardadDTO;
  int tarafeynID = t.TarafeynQarardadID;
}

Solution

  • You may want to check if your current selected count is not zero, before retrieving the cell content. Just a little code to help you.

     private void dtgTarafAvval_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if(dtgTarafAvval.SelectedCells.Count > 0)
            {
                CellValue = GetSelectedValue(dtgTarafAvval);
                //CellValue is a variable of type string.
    
            }
        }
    
        private string GetSelectedValue(DataGrid grid)
        {
            DataGridCellInfo cellInfo = grid.SelectedCells[0];
            if (cellInfo == null) return null;
    
            DataGridBoundColumn column = cellInfo.Column as DataGridBoundColumn;
            if (column == null) return null;
    
            FrameworkElement element = new FrameworkElement() { DataContext = cellInfo.Item };
            BindingOperations.SetBinding(element, TagProperty, column.Binding);
    
            return element.Tag.ToString();
        }
    

    PS: Above code works for SelectionUnit = 'FullRow'