Creating a Control From its Markup Representation
No words, just code!
1: public static T CreateControlFromMarkup<T>(String markup) where T: Control
2: {
3: StringBuilder builder = new StringBuilder();
4: TemplateControl page = HttpContext.Current.Handler as TemplateControl;
5: Int32 start = markup.IndexOf('<');
6: Int32 end = markup.IndexOf(':', start);
7: String tagPrefix = markup.Substring(start + 1, end - start - 1);
8:
9: foreach (String @namespace in typeof(T).Assembly.GetExportedTypes().Select(x => x.Namespace).OrderBy(x => x).Distinct())
10: {
11: builder.AppendFormat("<%@ Register Assembly=\"{0}\" Namespace=\"{1}\" TagPrefix=\"{2}\" %>\n", typeof(T).Assembly.FullName, @namespace, tagPrefix);
12: }
13:
14: builder.Append(markup);
15:
16: Control parentControl = page.ParseControl(builder.ToString());
17: T control = parentControl.Controls[0] as T;
18:
19: return (control);
20: }