开发者

obtain value from an anonymous object

开发者 https://www.devze.com 2023-03-17 17:06 出处:网络
I have a list of anonymous types in a DataGrid, and I need obtain the first value (EmployeeId), that is a integer.

I have a list of anonymous types in a DataGrid, and I need obtain the first value (EmployeeId), that is a integer.

when I compile the application I can see the values charged in the variable(selectedEmployee).

like this:

selectedEmployee = 
{
    EmployeeId = 402350236,
    OperatorNum = 12,
    StateName开发者_StackOverflow社区 = "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"
    ... 
}

this is my code when the user clic on the item in the grid.

var selectedEmployee = _employeedataGrid.CurrentCell.Item;

Also I try with this:

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

But the dataRowView is always Null. Not work...

how can I obtain the first value from that object?


The items in your grid are not DataRowView's, they are anonymous. You'll have to use reflection or alternatively, use dynamic.

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

On the other hand, it would be better if you used a strongly typed object instead. Create the class for it or use a Tuple (or other).


The DataRowView is null because CurrentCell.Item is an object with an anonymous type, not a DataRowView. The as operator casts the LHS to the type specified on the RHS or returns null if the item can't be cast to the RHS.

Since CurrentCell.Item is of an anonymous type you can't cast it to retrieve the EmployeeId. I suggest creating a class with the desired properties (call it the Employee class) and binding your datagrid to a collection of those Employees. Then you could say

var selectedEmployee = (Employee)_employeedataGrid.CurrentCell.Item;
int? selectedId = selectedEmployee == null? (int?)null : selectedEmployee.EmployeeId;
0

精彩评论

暂无评论...
验证码 换一张
取 消