Reputation: 528
I am designing a system that maps an object to a page through reflection, by looking at the field names and the property names, then attempting to set the values of the controls. The issue is that the system takes massive amounts of time to finish. I'm hoping that someone may be able to assist in speeding this up a little bit
public static void MapObjectToPage(this object obj, Control parent) {
Type type = obj.GetType();
foreach(PropertyInfo info in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)){
foreach (Control c in parent.Controls ) {
if (c.ClientID.ToLower() == info.Name.ToLower()) {
if (c.GetType() == typeof(TextBox) && info.GetValue(obj, null) != null)
{
((TextBox)c).Text = info.GetValue(obj, null).ToString();
}
else if (c.GetType() == typeof(HtmlInputText) && info.GetValue(obj, null) != null)
{
((HtmlInputText)c).Value = info.GetValue(obj, null).ToString();
}
else if (c.GetType() == typeof(HtmlTextArea) && info.GetValue(obj, null) != null)
{
((HtmlTextArea)c).Value = info.GetValue(obj, null).ToString();
}
//removed control types to make easier to read
}
// Now we need to call itself (recursive) because
// all items (Panel, GroupBox, etc) is a container
// so we need to check all containers for any
// other controls
if (c.HasControls())
{
obj.MapObjectToPage(c);
}
}
}
}
I realize that I can do this manually via
textbox.Text = obj.Property;
however, this defeats the purpose of making it so that we can map an object to the page without all the manual setting of values.
The 2 major bottlenecks I have identified are the foreach loops, seeing as it loops through each control / property and in some of my objects there are 20 or so properties
Upvotes: 1
Views: 230
Reputation: 35363
Instead of looping N*M, Loop properties once, put them into a dictionary and then use that dictionary while looping controls
Upvotes: 3