[英]Command not executing in row level ContextMenu on DataGrid in WPF C#
[英]Getting selected row off DataGrid when selecting a ContextMenu MenuItem on that row? WPF C#
我试图在右键单击某行并选择一个快捷菜单菜单项时获取选定的行值。 我正在使用DataTables填充我的数据网格。 这是我填写表格的方式:
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;
这是我尝试检索它的代码:
Group group = (Group)dg_unassigned.SelectedItem;
MessageBox.Show(group.Name);
这是我得到的错误:
无法转换类型为'System.Data.DataRowView'的对象
您无法将所选行作为组,因为您没有将itemsSource设置为组的集合(例如List <Group>)。
因此,在您的情况下,.SelectedItem给出一个DataRowView,您应该编写
DataRowView drv = (DataRowView)dg_unassigned.SelectedItem;
然后,您可以通过以下方式获取Group对象:
Group group = new Group { Name = drv["Name"].ToString() };
我不知道您的表格看起来如何,但是您可以使用以下方式访问表格中的任何字段
drv["nameOfTheField"].ToString();
之后,该代码应该可以工作了!
MessageBox.Show(group.Name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.