Oct 16, 2009, 12:48 PM
Method to populate any store with any generic list
Hi
I didn't want to write a store object populating routine for every control that uses a Store object. So instead, I wrote a method which takes the store - as set in your aspx page - and a generic list of ANY type and populates the control specify in the StoreID tag. You could go one step further and dynamically create your store fields based upon the property names of the objects stored within the generic list but I couldn't get that to work. Hope someone find this useful
I didn't want to write a store object populating routine for every control that uses a Store object. So instead, I wrote a method which takes the store - as set in your aspx page - and a generic list of ANY type and populates the control specify in the StoreID tag. You could go one step further and dynamically create your store fields based upon the property names of the objects stored within the generic list but I couldn't get that to work. Hope someone find this useful
public static void BindStoreToDataControl<T>(Store store, List<T> list)
{
if (list != null || list.Count > 0)
{
Type t = typeof(T);
//make a new instance of the class name we figured out to get its props
object o = Activator.CreateInstance(t);
//gets all properties
PropertyInfo[] props = o.GetType().GetProperties();
Object[] dataContainer = new Object[list.Count];
int y = 0;
foreach (T item in list)
{
int x = 0;
Object[] data = new Object[props.Length];
//this acts as datacolumn
foreach (PropertyInfo pi in props)
{
//this is the row+col intersection (the value)
string propertyValue = Convert.ToString(item.GetType().GetProperty(pi.Name).GetValue(item, null));
data[x] = propertyValue;
x++;
}
dataContainer[y] = data;
y++;
}
store.DataSource = dataContainer;
store.DataBind();
}
else
{
store.DataSource = new Object[] { };
store.DataBind();
}
}
<ext:ComboBox ID="combobox1"
StoreID="store1"
FieldLabel="Test"
runat="server"
Editable="false"
ReadOnly="true"
DisplayField="Name"
ValueField="ID"
Width="250">
</ext:ComboBox>
<ext:Store ID="store1" runat="server">
<Reader>
<ext:ArrayReader>
<Fields>
<ext:RecordField Name="ID" />
<ext:RecordField Name="Name" />
</Fields>
</ext:ArrayReader>
</Reader>
</ext:Store>