I am converting dataset to a Dynamic collection and binding it, this is working fine.Now when i need to add a new object which is empty to the collection . what i am trying is getting the ItemsSource of the datagrid and getting the first object inside the list. But it has some values inside it. How can i remove the values and bind a empty object using reflection.
Here is my code,
IEnumerable<object> collection = this.RetrieveGrid.ItemsSource.Cast<object>();
List<object> list = collection.ToList();
//i need to clear the values inside list[0]
object name = list[0];
//here i build the properties of the object, now i need to create an empty object using these properties and add it to the list
PropertyInfo[] pis = list[0].GetType().GetProperties();
Call Activator.CreateInstance
to create new instance. Then use PropertyInfo.SetValue
to set the string fields to empty.
Type requiredType = list[0].GetType();
object instance = Activator.CreateInstance(requiredType);
PropertyInfo[] pis = requiredType.GetProperties();
foreach (var p in pis)
{
if (p.PropertyType == typeof(string))
{
p.SetValue(instance, string.Empty);
}
}
Do note that Activator.CreateInstance
throws exception if the type doesn't have parameterless constructor.
If your unknown type has some known constructor then you can instantiate it using reflection.
// gets the Type
Type type = list[0].GetType();
// gets public, parameterless constructor
ConstructorInfo ci = type.GetConstructor(new Type[0]);
// instantiates the object
object obj = ci.Invoke(new object[0]);
Obviously that won't work when you don't have a simple parameterless constructor. If you know that the class constructor always takes a certain parameter, for example an integer value then you could modify the snippet above with new Type[] { typeof(int) }
and new object[] { someIntValue }
.
But whether this will create an "empty" object or not depends on the behaviour of the constructor.
If you then want to set some properties you can iterate over the PropertyInfos
returned by calling type.GetProperties()
and call SetValue
with the appropriate value.