I have a datagrid populated by a Linq query. When the focused row in the datagrid changes I need to set a variable equal to one of the properties in that object.
I t
DevExpress's xtraGridView has a method like this GetRowCellDisplayText(int rowHandle, GridColumn column). With this method, the following code returns the id from the anonymous type.
var _selectedId = view.GetRowCellDisplayText(rowHandle, "Id");
Though this does not provide an answer to the question "How can I get access to the anonymous object's property?", it still attempts to solve the root cause of the problem.
I tried this with devXpress version 11.1 and I can see that the question was first asked almost 2.5 years ago. Possibly the author of the question might have got an workaround or found the solution himself. Yet, I am still answering so that it might help someone.
Have you ever tried to use reflection? Here's a sample code snippet:
// use reflection to retrieve the values of the following anonymous type
var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 };
System.Type type = obj.GetType();
int clientid = (int)type.GetProperty("ClientId").GetValue(obj, null);
string clientname = (string)type.GetProperty("ClientName").GetValue(obj, null);
// use the retrieved values for whatever you want...
var result = ((dynamic)DataGridView.Rows[rowNum].DataBoundItem).value;
Hope this helps, am passing in an interface list, which I need to get a distinct list from. First I get an Anonymous type list, and then I walk it to transfer it to my object list.
private List<StockSymbolResult> GetDistinctSymbolList( List<ICommonFields> l )
{
var DistinctList = (
from a
in l
orderby a.Symbol
select new
{
a.Symbol,
a.StockID
} ).Distinct();
StockSymbolResult ssr;
List<StockSymbolResult> rl = new List<StockSymbolResult>();
foreach ( var i in DistinctList )
{
// Symbol is a string and StockID is an int.
ssr = new StockSymbolResult( i.Symbol, i.StockID );
rl.Add( ssr );
}
return rl;
}
As JaredPar guessed correctly, the return type of GetRow()
is object
. When working with the DevExpress grid, you could extract the desired value like this:
int clientId = (int)gridView.GetRowCellValue(rowHandle, "ClientId");
This approach has similar downsides like the "hacky anonymous type casts" described before: You need a magic string for identifying the column plus a type cast from object to int.
A generic solution for getting the value of a data item for a given key
public static T GetValueFromAnonymousType<T>( object dataitem, string itemkey ) {
System.Type type = dataitem.GetType();
T itemvalue = (T)type.GetProperty(itemkey).GetValue(dataitem, null);
return itemvalue;
}
Example:
var dataitem = /* Some value here */;
bool ismember = TypeUtils.GetValueFromAnonymousType<bool>(dataitem, "IsMember");