title: How to use ContextMenu to access cell value of DataGrid?
body: <p>Here is what I did using WPF / C#:</p>
  
  <ol>
  <li>Use DataGrid to display data from a DataTable. This step works fine. </li>
  <li>Add a ContextMenu to the DataGrid. This also seems to be fine as the context menu show up correctly. </li>
  <li>Use the context menu to access the cell selected in the DataGrid, and use the value of the cell for further work. This is the step I got stuck on. </li>
  </ol>
  
  <p>I have been researching and trying other similar SO questions in the past couple of days but no luck. Can someone please help me get this right?</p>
  
  <p>I use Visual Studio 2019 and it is a WPF Framework project. I tried the approach from dsfgsho. See link <a href="https://stackoverflow.com/questions/16822956/getting-wpf-data-grid-context-menu-click-row/16823720">Getting WPF Data Grid Context Menu Click Row</a></p>
  
  <pre><code>//  Originally from dsfgsho, with slight changes.
  
  private void MenuItem_Click(object sender, RoutedEventArgs e)
  {
      //Get the clicked MenuItem
      var menuItem = (MenuItem)sender;
  
      //Get the ContextMenu to which the menuItem belongs
      var contextMenu = (ContextMenu)menuItem.Parent;
  
      //Find the placementTarget
      var item = (DataGrid)contextMenu.PlacementTarget;
  
      //Get the underlying item, that you cast to your object that is bound
      //to the DataGrid (and has subject and state as property)
      var selected_tbl_name = (DataColumn)item.SelectedCells[0].Item;
      //****The last step is where I get confused and it also throws an exception. 
  }
  </code></pre>
  
  <p>XAML:</p>
  
  <pre><code>&lt;Grid&gt;
      &lt;DataGrid 
          x:Name="dataGrid_test" 
          ItemsSource="{Binding}" 
          SelectedItem="{Binding SelectedItemPorperty}"
          HorizontalAlignment="Left" 
          Height="369" 
          Margin="395,10,0,0" 
          VerticalAlignment="Top" 
          Width="381" 
          SelectionChanged="DataGrid_SelectionChanged"
          &gt;
          &lt;DataGrid.ContextMenu&gt;
              &lt;ContextMenu&gt;
                  &lt;MenuItem Header="Select" Click="MenuItem_Click"&gt;
                  &lt;/MenuItem&gt;
              &lt;/ContextMenu&gt;
          &lt;/DataGrid.ContextMenu&gt;
      &lt;/DataGrid&gt;
  &lt;/Grid&gt;
  </code></pre>
  
  <p>Regarding the last line of the function MenuItem_Click(object sender, RoutedEventArgs e): Since I am using the DataGrid with a DataTable, I am thinking the underlying item would be a DataTable cell. Is there a type for DataTable cell? I can't find it so I used DataCloumn. But an exception was thrown and it says "Specified argument was out of ranges of valid values. Parameter name: index".</p>