views:

312

answers:

1

Is there any method to select a column of the current row of a BindingSource whose DataSource is an anonymous class?

var userResults = from u in dataContext.Users
       join c in dataContext.Computers on u.ID equals c.UserID
       where doSearch
       && u.Name.Contains(userNameTextBox.Text)
       && u.UserName.Contains(userUsernameTextBox.Text)
       select new { u.Name, u.UserName, u.Branch, c.Installations, u.ID };
userBindingSource.DataSource = userResults;

I want to get the current value of u.ID.

+1  A: 

The problem here is that items in the BindingSource are of type Object and you need to convert them back to their anonymous type, and you can't do that.... actually, you can (check the "Casting to anonymous types" section), but it's a clever trick that might not work in the future.

Other (better) options to get the value of a property:

  • Use a concrete type instead of an anonymous type
  • Use reflection to get the value of the property
  • C# 4.0 only: Use the dynamic keyword then call the property you need
  • Get the value in the bound control (for example, if your datasource is bound to a DataGridView, get the value of the datagridview cell instead of the binding source value)
Meta-Knight
But how does the .NET Framework solve this problem? If I want to bind another BindingSource to a sub-list of my current one, I just have to set the string property `DataMember`, how is this member variable resolved from the (maybe anonymous) DataSource object?
Manuel Faux
From what I could find, I think it uses reflection to find the bound property's value.
Meta-Knight