Here is what I did using WPF / C#:
- Use DataGrid to display data from a DataTable. This step works fine.
- Add a ContextMenu to the DataGrid. This also seems to be fine as the context menu show up correctly.
- 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.
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?
I use Visual Studio 2019 and it is a WPF Framework project. I tried the approach from dsfgsho. See link Getting WPF Data Grid Context Menu Click Row
// 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.
}
XAML:
<Grid>
<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"
>
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Select" Click="MenuItem_Click">
</MenuItem>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
</Grid>
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".