0

How can I replace a string with UserControl?

if string = [$control1$]

replace with control1.ascx

4 Answers4

1

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
  • 489,969
  • 99
  • 883
  • 1,009
1

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 How to a string can turn a UserControl 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.

Community
  • 1
  • 1
Keith
  • 150,284
  • 78
  • 298
  • 434
  • This thread explains it a little better, http://stackoverflow.com/questions/1535365/how-to-a-string-can-turn-a-usercontrol –  Dec 15 '09 at 21:53
0

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
  • 3
  • 1
  • 2
0

Say the template string is: {product_thumbnail} | {product_title} | {product_price} and you want to replace the each text in the brackets ({}) with a control. Here is how I did it.

string templateString = "{product_thumbnail}  | {product_title}  | {product_price} ";
Regex d = new Regex("\\{\\w+\\}", RegexOptions.Multiline);
MatchEvaluator matchEval = RegexReplaceEvaluator;
string r = d.Replace(templateString, matchEval);

private string RegexReplaceEvaluator(Match match)
{
  string matchValue = match.Value.Trim('}');
  matchValue = matchValue.Trim('{');
  Control toAdd = null;
  switch (matchValue)
  {
     case "product_thumbnail":
          toAdd = this.LoadControl("ThumbnailImage.ascx", DetailsRow);
     break;
     case "product_price":
          toAdd= this.LoadControl("Price.ascx", DetailsRow);
   .....
  }   //end switch statement

if (toAdd != null) {
                PlaceHolder1.Controls.Add(new LiteralControl(templateString.Substring(stringIndexMarker, match.Index - stringIndexMarker)));
                stringIndexMarker = match.Index + match.Length;
                PlaceHolder1.Controls.Add(toAdd);
            }
            return match.Value;
}//end method

The code above simply does the following: 1. Takes in the template string. (string with text to the replaced with controls). 2. Declares a placeholder (to hold the final output). 3. Iterates through the string. When it finds a string to replaced with a control it does takes the text before the this, adds it as a text to the placeholder and also add the control.

Hope this makes sense.

CPhelefu
  • 128
  • 1
  • 5