Search code examples
c#wpfdatagridwpfdatagrid

Getting selected row off DataGrid when selecting a ContextMenu MenuItem on that row? WPF C#


I am trying to get the selected row values when a row is right clicked and a contextmenu menuitem is selected. I am using DataTables to fill my datagrid. Here is how I fill the table:

MySqlDataAdapter da = new MySqlDataAdapter("SELECT id as ID, name as Group_Name,   order_ascend as Display_Order FROM groups", MyConString);
DataSet ds = new DataSet(); 
da.Fill(ds);
dg_unassigned.ItemsSource = ds.Tables[0].DefaultView;

Here is my code in trying to retrieve it:

Group group = (Group)dg_unassigned.SelectedItem;
MessageBox.Show(group.Name);

This is the error I get:

Unable to cast object of type 'System.Data.DataRowView'


Solution

  • You cannot get the selected row as a Group because you didn't set the itemsSource as a collection of Group (a List< Group> for example).

    So in your case the .SelectedItem gives a DataRowView, you shoud write

    DataRowView drv = (DataRowView)dg_unassigned.SelectedItem;
    

    Then you can get a Group object this way:

    Group group = new Group { Name = drv["Name"].ToString() };
    

    I don't know how your table looks like, but you can access any field in your table with

    drv["nameOfTheField"].ToString();
    

    After that this code should work!

    MessageBox.Show(group.Name);