Binding a structure containing a hashtable to a grid
I'm trying to create a pivot of a translation table. Basically the table is like that :
SystemText(Category, Name, LanguageCode, Text)
I have created a model 开发者_JS百科object which has these fields as properties and I'm using NHibernate to get the data from the database.
Now what I want to display is a grid to edit the translations that will display on the same line the category, the name of the text and all the available languages (languages that are not fixed in advance). For example :
Category | Name | English | French | German
I've managed to create a Linq query to create the pivot that I will need to do that. It looks like that
Dim test = From systemText In _systemTexts _
Group systemText By Key = New With {Key systemText.TextCategory, Key systemText.TextName} Into g = Group _
Select New With {Key .TextCategory = Key.TextCategory, _
Key .TextName = Key.TextName, _
.Languages = g.ToDictionary(Function(st) st.LanguageCode, Function(st) st.Description)}
Now the only trouble I have is to bind the objects to my gridlist. I would create the columns of the grid dynamically when the form is loading, depending on the languages available. I thought that using something like Languages("EN") in the DataMember property would work, but it doesn't seem so.
I'm a bit blocked now, I thought about using something else to replace the Dictionary for the languages but I don't really see what I can use.
So, after some trial and error I ended finding some ways to do that.
The first, and one of the most complex ways of doing it I have found was was given by Vladimir Burodov on this blog post. The idea basically is to dynamically create an anonymous type that has a property for each key in the Dictionary. It's very clever and very useful, but a bit overkill for the little task I needed.
Another way around was using Custom Property Descriptors. The idea is to create a custom list type that will, when asked for the special property call a custom function that will send back the value. Examples of this method can be seen here. Again unfortunately I couldn't use this method because the grid component I am using cannot use the custom property descriptors.
I also thought about using Dynamic Linq to generate dynamic queries where I would have been able to change the property names of the query result (see this Scottgu's article) but I didn't want to use another library just for the simple thing I needed.
Finally what I endend doing was dynamically creating a DataTable, inserting the result of the Linq query in it, binding the DataTable to the grid and finally listening to the RowUpdated event and do the CRUD operations to the NHibernate collections. It works quite nicely and the code is easy to understand.
精彩评论