簡體   English   中英

從匿名 object 獲取值

[英]obtain value from an anonymous object

我在 DataGrid 中有一個匿名類型列表,我需要獲取第一個值 (EmployeeId),即 integer。

當我編譯應用程序時,我可以看到變量(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。 不行...

如何從 object 中獲取第一個值?

網格中的項目不是DataRowView的,它們是匿名的。 您必須使用反射,或者使用dynamic

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

另一方面,最好使用強類型 object 代替。 為其創建 class 或使用Tuple (或其他)。

DataRowView是 null 因為CurrentCell.Item是一個匿名類型的 object,而不是 DataRowView。 as運算符將 LHS 轉換為 RHS 上指定的類型,如果項目無法轉換為 RHS,則返回 null。

由於CurrentCell.Item是匿名類型,因此您不能將其強制轉換為檢索 EmployeeId。 我建議創建一個具有所需屬性的 class(稱為Employee類)並將您的數據網格綁定到這些員工的集合。 那你可以說

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM