[英]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.
我正在使用DataTables填充我的数据网格。 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'
无法转换类型为'System.Data.DataRowView'的对象
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). 您无法将所选行作为组,因为您没有将itemsSource设置为组的集合(例如List <Group>)。
So in your case the .SelectedItem gives a DataRowView, you shoud write 因此,在您的情况下,.SelectedItem给出一个DataRowView,您应该编写
DataRowView drv = (DataRowView)dg_unassigned.SelectedItem;
Then you can get a Group object this way: 然后,您可以通过以下方式获取Group对象:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.