You've created an
anonymous type[
^] to represent the projection. There is generally no way to cast that to an object and read its properties short of reflection.
One simple but fragile approach would be to use
C#'s dynamic
type[
^], which will hide the reflection code from you:
dynamic selectedItem = memebersdataGrid.SelectedItem;
int id = selectedItem.ID;
The major down-side is that you will have no intellisense, and no compile-time checks. If you spell the property name wrong, or use the wrong case, you'll find out at runtime when you get a
RuntimeBinderException
thrown.
Rolling your own reflection won't be any better, and will potentially decrease the performance:
object selectedItem = memebersdataGrid.SelectedItem;
Type itemType = selectedItem.GetType();
PropertyInfo prop = itemType.GetProperty("ID");
int id = (int)prop.GetValue(selectedItem, null);
The safer solution is to create a specific class to represent the projection, and use that instead:
public class MemberProjection
{
public int ID { get; set; }
public DateTime? RegTime { get; set; }
public string NumberPhone { get; set; }
public string FatherName { get; set; }
public string Name { get; set; }
}
...
private void Load()
{
var st = (from s in db.RegFee_Tbl
join o in db.User_Tbl on s.NumberPhone equals o.NumberPhone
select new MemberProjection { ID = s.ID, RegTime = s.RegTime, NumberPhone = s.NumberPhone, FatherName = o.FatherName, Name = o.Name }).ToList();
membersdataGrid.ItemsSource = st;
datagrid = membersdataGrid;
}
...
int id = ((MemberProjection)memebersdataGrid.SelectedItem).ID;
NB: With any of these approaches, remember that the
SelectedItem
may be
null
. You'll want to check for that before trying to access one of its properties.