I’m having a bit of problem with casting and datagrids. I have a LINQ to SQL query:
var contents = from content in context.Contents
join contenttype in context.ContentTypes on content.ContentTypeID equals contenttype.ContentTypeID
select new { content, contenttype };
and then that gets put into a datagrid (not all of the data, only select columns such as content.ContentID etc).
The problem is that when I try and get the selected row, I cannot. I have the following code:
Console.WriteLine((Content)dataGrid1.SelectedItem);
which fails due to the fact that the type is both Content and ContentType – is there a way around this? The error I get is:
Unable to cast object of type '<>f__AnonymousType0`2[iAdvert_Desktop.Content,iAdvert_Desktop.ContentType]' to type 'iAdvert_Desktop.Content'.
If I just write the SelectedItem I get: { content = iAdvert_Desktop.Content, contenttype = iAdvert_Desktop.ContentType } – is there a way I can do something like: (Content)dataGrid1.SelectedItem['Content'];?
I think this post may answer your question:
How do I get values from SelectedItem in ComboBox with Linq and C# 3.5