Hi,
I'm trying to clean up some pretty ugly form population code in the code behind of an aspx that looks like this:
SchoolCensus1.Checked = (bool)questions[0].SchoolCensus1;
SchoolCensus1Info.Text = questions[0].SchoolCensus1Info;
SchoolCensus2.Checked = (bool)questions[0].SchoolCensus2;
SchoolCensus2Info.Text = questions[0].SchoolCensus2Info;
SchoolCensus3.Checked = (bool)questions[0].SchoolCensus3;
SchoolCensus3Info.Text = questions[0].SchoolCensus3Info;
This goes on for quite a while.
What I have so far is this:
Type questionsType = questions[0].GetType();
PropertyInfo[] properties = questionsType.GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.PropertyType == typeof(Nullable<Boolean>))
{
CheckBox chkBox = container.FindControl(property.Name) as CheckBox;
if (chkBox != null)
chkBox.Checked = (bool)property.GetValue(questions[0], null);
}
else if (property.PropertyType == typeof(String))
{
TextBox txtBox = container.FindControl(property.Name) as TextBox;
if (txtBox != null)
txtBox.Text = (string)property.GetValue(questions[0], null);
}
}
This does what I need it to do, but I want to break out this part into a method to DRY it up a little more:
TextBox txtBox = container.FindControl(property.Name) as TextBox;
if (txtBox != null)
txtBox.Text = (string)property.GetValue(questions[0], null);
Any advice as to the method needed to cope with the changing Control type? I'm guessing generics is what I need, but that really isn't something I have much experience in.
Thanks in advance!