Rendering a server-side control using HTMLTextWriter makes control lose standard functionality (i.e. Click eventhandler)

anpatel picture anpatel · Mar 2, 2012 · Viewed 9k times · Source

I want to add Server-Side controls (CheckBoxLists & Button):

ChkBoxLst1 & ChkBoxLst2 & Button1 through Code-behind and then use an HTMLTextWriter to render the control.

I can't seem to be able to do this.

All of the above in a Visual WebPart.

What I have tried:
Global:

CheckBoxList ChkBoxLst2 = new CheckBoxList();
Button Bttn2 = new Button();
Label lbl2 = new Label(); 

StringWriter stringWriter = new StringWriter(); 

Page Load:

using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
        {
            ChkBoxLst2.Items.Add(new ListItem("Three", "3"));
            ChkBoxLst2.Items.Add(new ListItem("Four", "4"));

            ChkBoxLst2.RenderControl(writer);
            lbl2.RenderControl(writer);
            Bttn2.Click += new EventHandler(this.Bttn2_Click);
            Bttn2.Text = "Click this HTMLText WriteButton!";
            Bttn2.RenderControl(writer); 

        }

        spn.InnerHtml = stringWriter.ToString(); 

Event Handler:

 void Bttn2_Click(Object sender, EventArgs e)
    {
        foreach (ListItem item in ChkBoxLst2.Items)
        {
            if (item.Selected == true)
            {
                if (IsPostBack)
                {
                    lbl.Text += item.Text + ", ";
                }
            }
        }
    }

The EventHandler does not get triggered and the selected values do not get saved the way I have done it above. Any ideas as to why not? I've tried a comparison of two checkbox lists, but the HTMLTextWriter implementation did not work whereas the simple .NET did of the same thing
all in all I think its my implementation of an HTMLTextWriter/how I add the server control.

Note that the spn is a literal span control in the markup.

Answer

Shlomi Komemi picture Shlomi Komemi · Mar 2, 2012

try this method to render controls into an html string:

    public static string ControlRenderToString(Control tmpControl)
    {
        string Content;

        System.IO.StringWriter sWriter = new System.IO.StringWriter();
        HtmlTextWriter htwObject = new HtmlTextWriter(sWriter);
        tmpControl.RenderControl(htwObject);

        Content = sWriter.ToString();
        sWriter.Close();

        return Content;
    }