DataGrid to DataRowView
本文关键字:DataRowView to DataGrid | 更新日期: 2023-09-27 17:59:21
当用户点击时,我需要从dataGrid中向datarowview中收取项目值,以获得第一个值"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]);
.......
}
这是因为_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]);
.......
}
这就是您需要的
DataRowView view = _employeedataGrid.Items[_employeedataGrid.SelectedIndex] as DataRowView;
//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();
只要选择了项,就可以直接获得每列的值,而无需循环。第1列将有一个索引Row.ItemArray[0],第2列将有索引Row.Item Array[1]等。这一切都取决于您的任务。
var EmpID = Convert.ToInt32(((DataRowView)_employeedataGrid.SelectedItem).Row.ItemArray[0].ToString());