Populating a list box with variable names from LINQ generated class
I'm quite new to Visual Basic - using Visual Studio 2008 and can't seem to find a way to do the following:
I have a few tables in a SQL Server database and have used LINQ to SQL to create classes of those tables.
Here's a cut down example of what I'd like: listbox1 filled with table names - APS, SMPS, WCPC, CFLAPS Then from the Se开发者_如何学PythonlectedIndexChanged event, listbox2 should populate column headers of the selected table.
I have no issues getting data from the database, and can access all of these headers through the anonymous type objects created from a LINQ query (eg APS.ID, APS.count etc), but populating a listbox with these variable names rather than the data inside them seems rather elusive.
This is probably a cross platform coding question rather than VB specific, so if you have a solution in C# or whatever I'd be happy if you could let me know.
What I would suggest is using reflection to find the name of each property. I found this C# example you may find useful.
What you probably need here is to analyze an expression tree. Basically, if you have a LINQ to SQL query, you get an IQueryable object that has the "expression" property. This property should provide you the info about your anonymous types and their properties. Here is a good starting point for you (yes, it's written for C#, but it works for VB as well): http://blogs.msdn.com/charlie/archive/2008/01/31/expression-tree-basics.aspx
精彩评论