C#-从匿名对象获取值

我在DataGrid中有一个匿名类型的列表,我需要获取第一个值(EmployeeId),它是一个整数.

当我编译应用程序时,我可以看到变量(selectedEmployee)中的值.

像这样:

selectedEmployee = 
{
    EmployeeId = 402350236,
    OperatorNum = 12,
    StateName = "Active",
    Name = "Robert",
    LastName = "Tedd Zelaya",
    Password = "abcd",
    DateBegin = {13/07/2011 0:00:00},
    DateEnd = {23/07/2011 0:00:00},
    Telephone = "8869-2108",
    Address = "Santa Barvara"
    ... 
}

当用户选择网格中的项目时,这是我的代码.

var selectedEmployee = _employeedataGrid.CurrentCell.Item;

我也尝试这样做:

DataRowView dataRowView = _employeedataGrid.CurrentCell.Item as DataRowView;
            var idEmployee = 0;
            if (dataRowView != null) 
            {
                idEmployee = Convert.ToInt32(dataRowView.Row[0]);
            }

但是dataRowView始终为Null.不行…

如何从该对象获取第一个值?

解决方法:

网格中的项目不是DataRowView的,它们是匿名的.您必须使用反射,或者使用动态.

dynamic currentItem = _employeedataGrid.CurrentCell.Item;
int idEmployee = currentItem.EmployeeId;

另一方面,最好改用强类型对象.为此创建类或使用元组(或其他).

上一篇:c#-在WPF中实现拖放后,无法从网格列中选中或取消选中复选框


下一篇:WPF DataGrid HeaderTemplate神秘填充