Is is possible in runtime create class from DataTable where ColumnName will be dynamic class properties?
+1
A:
Yes (using Reflection.Emit), but it's a bad idea.
What are you trying to do?
SLaks
2010-04-23 12:55:45
I have RadGridView which has some problems when I use dataTable as source for him. But when I use List<class> everything works fine. Any ideas?
Polaris
2010-04-23 12:58:21
You should ask that as a separate question.
SLaks
2010-04-23 13:00:00
A:
Reading your comments, I undestood your mean. Just use Generics: using List fields to generate the objects. The code is quite simple:
public class DynClass<T, P>
{
public DynClass()
{
_fields = new Dictionary<T, P>();
}
private IDictionary<T, P> _fields;
public IDictionary<T, P> Fields
{
get { return _fields; }
}
}
public class TestGenericInstances
{
public TestGenericInstances()
{
Client cli = new Client("Ash", "99999999901");
/* Here you can create any instances of the Class.
* Also DynClass<string, object>
* */
DynClass<string, Client> gen = new DynClass<string, Client>();
/* Add the fields
* */
gen.Fields.Add("clientName", cli);
/* Add the objects to the List
* */
List<object> lstDyn = new List<object>().Add(gen);
}
}
Erup
2010-04-23 12:58:31
Every time I can have different columns with different names and types. Can you tell me about your variant in details or show me a peace of code?
Polaris
2010-04-23 13:10:56
+1
A:
If you have C# 4 you can make use of the new dynamics feature and the ExpandoObject
. You can read a tutorial about it here.
klausbyskov
2010-04-23 12:59:13
+1
A:
With C# 4, you can do this
dynamic foo = new ExpandoObject();
// mimic grabbing a column name at runtime and adding it as a property
((IDictionary<string, object>)foo).Add("Name", "Apple");
Console.WriteLine(foo.Name); // writes Apple to screen
Not recommending it or anything, but it shows you it is possible.
Anthony Pegram
2010-04-23 13:03:20