I've got this XML file;
it's an export of the Northwind Employees table. I load this up with LINQ to XML and then I want to databind it into a Windows Forms ListBox.
In the ListBox, I want to display a concatenation of the firstName and lastName but I also want to be able to get back to the XElement representing that item in the XML when someone changes the selected item.
I could use the tag but I kind of thought "Hmm, I can just use some anonymous tuple that has both the String and the XElement in it", i.e. using the code below where employees is just an XElement representing the root of the XML in the picture above;
listBox1.DataSource =
(
from e in employees.Descendants("employee")
select new
{
Element = e,
Text = string.Format("{0} {1}",
(string)e.Attribute("firstName"),
(string)e.Attribute("lastName"))
}
).ToList();
and that all seemed very nice until I kind of thought (as always seems to be the way with anonymous types);
So, how will I get back to my Element value when someone clicks on the ListBox items because in my event handler I can't access an anonymous type (without reflection).
For me, this was easily enough solved because I don't actually want the whole anonymous type in my handler, I just want the XElement so I can do something like;
listBox1.DisplayMember = "Text";
listBox1.ValueMember = "Element";
and then I display the bit of the anonymous type that I want to display and I have access to the other bit of the anonymous type and I'll never actually "see" the anonymous type instance again.
This falls into the category of "needs more thought" as there's something general-purpose kicking around I there I think.
Posted
Mon, Sep 10 2007 4:39 AM
by
mtaulty