Monday, December 20, 2010

C#: Clone HtmlControl

HtmlControl does not inherit ICloneable. So this method mimic's what's missing.


private HtmlControl CopyControl(HtmlControl sourceControl, Dictionary controlAttributes, string suffix)
{
Type controlType = sourceControl.GetType();
HtmlControl targetControl = (HtmlControl)controlType.InvokeMember(String.Empty, BindingFlags.CreateInstance, null, null, null);
targetControl.Attributes.Clear();
foreach (PropertyInfo propertyInfo in controlType.GetProperties())
{
if (propertyInfo.CanWrite)
{
if (propertyInfo.Name == "ID")
{
targetControl.ID = targetControl.TagName + suffix;
}
else
{
if (controlType.Name == "HtmlSelect")
{
//For HtmlSelect's, InnerText or InnerHtml can not be modified
//So ignore one, and use the other one for adding the individual items
if (propertyInfo.ToString() == "System.String InnerText")
continue;
else if (propertyInfo.ToString() == "System.String InnerHtml")
{
HtmlSelect sc = (HtmlSelect)sourceControl;
HtmlSelect tc = (HtmlSelect)targetControl;
foreach (var item in sc.Items)
{
tc.Items.Add(item.ToString());
}
}
else
{
propertyInfo.SetValue(targetControl, propertyInfo.GetValue(sourceControl, null), null);
}
}
else
{
propertyInfo.SetValue(targetControl, propertyInfo.GetValue(sourceControl, null), null);
}
}
}
}

No comments:

Post a Comment

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.