0

Is there any ways/possibilities that I can replace a string with a UserControl?

apart from LoadControl and adding it to another control like page or placeholder.

The reason is that a user add a content on the page and put a string like {uc:test} and I would like to parse this text and replace {uc:test} with a UserControl.

in other words ; The user input will be "bla bla bla {uc:test} bla bla", when I retrieve it from database how can I inject usercontrol and replace it with {uc:test}

thanks.

Cem
  • 889
  • 2
  • 10
  • 22

2 Answers2

1

Try the LoadControl method to dynamically load user controls and add them to your page during postback.

Control someControl = LoadControl("~/SomeControl.ascx");

You could... Add it to your page's control collection:

        this.Page.Controls.Add(someControl);

Or... Add it to another control's control collection

        someExistingPlaceHolder.Controls.Add(someControl);

How about getting the tags like this using regex

List<string> fields = new List<string>(); 
foreach(Match match in Regex.Matches(str, @"\{([^\}]*)\}")) { 
    fields.Add(match.Groups[1].Value); 
} 
CRice
  • 12,279
  • 7
  • 57
  • 84
  • the user input will be "bla bla bla {uc:test} bla bla", when I retrieve it from database how can I inject usercontrol and replace it with {uc:test} – Cem Oct 08 '09 at 03:01
  • 1
    Using string manipulation to detect { and } to begin with, so string.IndexOf() to get positions for reserved tag then you can add "bla bla bla" as a literal control which will render as text, add the uc:test control, add "bla bla" as a literal control – CRice Oct 08 '09 at 03:05
  • After you get the string you can use stringName.Replace("{uc:test}", "_userControlHere_"); – Michael Todd Oct 08 '09 at 03:12
0

If you want all of the user input to be respected, including any control references they've included, use ParseControl:

string markup = input.Replace("{","<").Replace("}",">");
Control control = this.Page.ParseControl(markup);

this.Page.Controls.Add(control);

This will create a new Control which represents all the text ("blah blah") as Literal child controls, as well as create new instances of <uc:test> as nested child controls.

Rex M
  • 142,167
  • 33
  • 283
  • 313
  • ParseControl(@"bla bla bla bla bla");... how do you register the control uc:test so that it is not an unknown server tag? I tried <%@ Register TagPrefix...> in an example but no luck. – CRice Oct 08 '09 at 07:07
  • When registered in web.config the control is found but does not render... the surrounding text does – CRice Oct 08 '09 at 07:15
  • @Boon have you tried adding that particular control to the page explicitly and see if it works correctly? – Rex M Oct 15 '09 at 00:30