我需要在用户点击时从dataGrid收取项目值,进入数据视图以获取第一个值“IdEmployee”并分配给变量。
这是我的方法,问题是我的变量dataRowView是Null!
我该如何解决这个问题?
private void _employeedataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
DataRowView dataRowView = _employeedataGrid.CurrentCell.Item as DataRowView;
var idEmployee = Convert.ToInt32(dataRowView.Row[0]);
.......
}
答案 0 :(得分:2)
这是因为_employeedataGrid.CurrentCell.Item
无法转换为DataRowView
。为什么不尝试CurrentRow
而不是CurrentCell
?:
private void _employeedataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
DataRowView dataRowView = _employeedataGrid.CurrentRow.Item as DataRowView;
var idEmployee = Convert.ToInt32(dataRowView.Row[0]);
.......
}
答案 1 :(得分:1)
这就是你需要的东西
DataRowView view = _employeedataGrid.Items[_employeedataGrid.SelectedIndex] as DataRowView;
答案 2 :(得分:0)
//during datagrid events like RowEditEnding, SelectionChange event 'e' will be very useful as...
DataGridRow row1 = e.Row;
int row_index = ((DataGrid)sender).ItemContainerGenerator.IndexFromContainer(row1);
//or try this if works
int i_row = e.Row.GetIndex();
答案 3 :(得分:0)
只要选择了该项,就可以直接获取每一列的值,而无需循环。第1列的索引为Row.ItemArray [0],第2列的索引为Row.ItemArray [1]等。这完全取决于您的任务。
var EmpID = Convert.ToInt32(((DataRowView)_employeedataGrid.SelectedItem).Row.ItemArray[0].ToString());