views:

157

answers:

2

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.

+1  A: 

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
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
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
After you get the string you can use stringName.Replace("{uc:test}", "_userControlHere_");
Michael Todd
A: 

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
ParseControl(@"bla bla bla <uc:test id=""xx"" runat=""server"" /> 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
When registered in web.config the control is found but does not render... the surrounding text does
CRice
@Boon have you tried adding that particular control to the page explicitly and see if it works correctly?
Rex M