views:

177

answers:

3

How can I replace a string with UserControl?

if string = [$control1$]

replace with control1.ascx

+1  A: 

You can't set a string to a control, as they are completely different types.

You can set a string to the text of a control, as the text is of type string:

string myString = control.Text;
Oded
A: 

Also you can render control to string:

StringWriter sw = new StringWriter();
HtmlTextWriter htmlw = new HtmlTextWriter(sw);
ctr.RenderControl(htmlw);
string stringText = sw.ToString();
Igor Ivanov
+1  A: 

Do you mean the HTML output by the user control if it is loaded into a page?

Try this:

using System.Web.UI;

public static string RenderToString(this Control control)
{
    var sb = new StringBuilder();
    using (var sw = new StringWriter(sb))
    using (var textWriter = new HtmlTextWriter(sw))
    {
        control.RenderControl(textWriter);
    }

    return sb.ToString();
}

Update:

Ahh - first you need the parser for the strings (which appears to be what http://stackoverflow.com/questions/1535365 is about) - this will give you the names of the user controls to replace.

From @Boon's answer to that question:

static List<string> FindTokens( string str ) 
{
    List<string> fields = new List<string>(); 
    foreach(Match match in Regex.Matches(str, @"\{([^\}]*)\}")) 
    { 
        fields.Add(match.Groups[1].Value); 
    }
    return fields;
}

So then we need a function to load the controls:

Dictionary<string, string> GetControls( List<string> controlNames )
{
    Dictionary<string, string> retval = new Dictionary<string, string>();
    foreach( string controlName in controlNames ) {
    {
        // load the control
        Control ctrl = LoadControl("~/AllowedDynamicControls/" + controlName + ".ascx");

        // add to the dictionary
        retval.Add(controlName, ctrl.RenderToString() );
    }
}

Then use the results of this to replace the tokens:

var tokensInString = FindTokens(input);
var tokenContent = GetControls( tokensInString );

foreach( var pair in tokenContent ) 
{
    input = input.Replace( "[$" + pair.Key + "$]", pair.Value);
}

There's probably more efficient way to do this - I've used a replace as a quick example.

Keith
This thread explains it a little better, http://stackoverflow.com/questions/1535365/how-to-a-string-can-turn-a-usercontrol
Neil