从匿名对象获取值

时间:2011-07-05 18:28:18

标签: c# datagrid anonymous-types

我在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。不行......

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

2 个答案:

答案 0 :(得分:4)

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

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

另一方面,如果你使用强类型对象会更好。为它创建类或使用Tuple(或其他)。

答案 1 :(得分:0)

DataRowView为null,因为CurrentCell.Item是具有匿名类型的对象,而不是DataRowView。 as运算符将LHS转换为RHS上指定的类型,如果无法将项目强制转换为RHS,则返回null。

由于CurrentCell.Item属于匿名类型,因此无法将其强制转换为检索EmployeeId。我建议创建一个具有所需属性的类(称为Employee类)并将datagrid绑定到这些Employees的集合。然后你可以说

var selectedEmployee = (Employee)_employeedataGrid.CurrentCell.Item;
int? selectedId = selectedEmployee == null? (int?)null : selectedEmployee.EmployeeId;
相关问题