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

StackOverflow https://stackoverflow.com/questions/9536168

Question

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.

Was it helpful?

Solution

Although you have rendered these controls to the browser, the controls are not part of the control tree of the page, and will not even exist on postback. Any dynamically-added controls need to be added on every request.

Why play with HtmlTextWriter at all? Simply add the controls to the page during Page_Load, and they'll be rendered for you. Do so outside of the "if (!Page.IsPostBack)" and they'll be there every time the page loads, which is what you want.

OTHER TIPS

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;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top