I have a Generic list of Objects. Each object has 9 string properties. I want to turn that list into a dataset that i can pass to a datagridview......Whats the best way to go about doing this?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
You could create an extension method to add all property values through reflection:
You may want to check out
http://www.codeproject.com/KB/vb/List2DataSet.aspx
Gives a few different approaches.
I've written a small library myself to accomplish this task. It uses reflection only for the first time an object type is to be translated to a datatable. It emits a method that will do all the work translating an object type.
Its the fastest solution i know (thats why i developed it :-) ). You can find it here: ModelShredder on GoogleCode
Currently it is only supporting translation to a DataTable. As you phrased your question, this should be sufficient. Support for DataSets (think of a simple reverse ORM) is already developed, it will be released in two weaks when i am back from vacation :-)
Have you tried binding the list to the datagridview directly? If not, try that first because it will save you lots of pain. If you have tried it already, please tell us what went wrong so we can better advise you. Data binding gives you different behaviour depending on what interfaces your data object implements. For example, if your data object only implements
IEnumerable
(e.g.List
), you will get very basic one-way binding, but if it implementsIBindingList
as well (e.g.BindingList
,DataView
), then you get two-way binding.I apologize for putting an answer up to this question, but I figured it would be the easiest way to view my final code. It includes fixes for nullable types and null values :-)
One option would be to use a System.ComponenetModel.BindingList rather than a list.
This allows you to use it directly within a DataGridView. And unlike a normal System.Collections.Generic.List updates the DataGridView on changes.