title: WPF Datagrid single click row to open new Page
body: <p>My first post here! And new to coding!...</p>
  
  <p>I have a WPF Datagrid in a Frame on a Page. I would like to click (preferably single click) on a row and use the ID value stored in one of the columns to Navigate to (open) a new Page.</p>
  
  <p>Using MouseDoubleClick sometimes I can double click row to open a Page. But sometimes it is throwing:
  "An unhandled exception of type 'System.NullReferenceException' occurred in program.exe
  Additional information: Object reference not set to an instance of an object."</p>
  
  <p>on line (see code behind below for complete method): </p>
  
  <pre><code>string ID = ((DataRowView)PersonDataGrid.SelectedItem).Row["PersonID"].ToString();
  </code></pre>
  
  <p>XAML:</p>
  
  <pre><code>&lt;DataGrid x:Name="PersonDataGrid" AutoGenerateColumns="False" 
       SelectionMode="Single" SelectionUnit ="FullRow"      
       MouseDoubleClick="PersonDataGrid_CellClicked"  &gt;
    &lt;DataGrid.Columns&gt;
        &lt;DataGridTextColumn Binding="{Binding Path=PersonID}" 
            ClipboardContentBinding="{x:Null}" Header="ID"  /&gt;
    &lt;/DataGrid.Columns&gt;
    &lt;DataGrid.CellStyle&gt;
        &lt;Style TargetType="DataGridCell" BasedOn="{StaticResource myDataGridCellStyle}"&gt;
             &lt;EventSetter Event="DataGridCell.MouseLeftButtonDown" Handler="PersonDataGrid_CellClicked"/&gt;
        &lt;/Style&gt;
     &lt;/DataGrid.CellStyle&gt;
  &lt;/DataGrid&gt;
  </code></pre>
  
  <p>Code Behind:</p>
  
  <pre><code>private void PersonDataGrid_CellClicked(object sender, MouseButtonEventArgs e)
  
      {
          string ID = ((DataRowView)PersonDataGrid.SelectedItem).Row["PersonID"].ToString();
  
          SelectedPersonID = Int32.Parse(ID);
  
          this.NavigationService.Navigate(new PersonProfile());
      }
  </code></pre>
  
  <p>Is there a better way to open the PersonProfile Page? Is there an easy way to open the Page using single click on a row?</p>
  
  <p>Thanks.</p>