Search code examples
c#asp.net.netcustom-server-controls

ASP.NET CheckBox AutoPostBack not firing


I have a checkbox that I am adding to a server control. This checkbox is not getting the usual onclick...__doPostBack() call added to it either. This results in it not causing a postback like I would like it to.

private void CreateGrid()
    {
        StringWriter sWriter = new StringWriter();
        HtmlTextWriter writer = new HtmlTextWriter(sWriter);

        GridItem.ID = "gridItem";

        GridHeader.ID = "gridHeader";
        GridHeader.Attributes["class"] += " no-select";

        GridCount.ID = "GridCount";

        GridDescription.ID = "GridDescription";

        if (cBoxID == null) tBox.Visible = false;
        else
        {
            tBox.ID = cBoxID;
            tBox.AutoPostBack = true;
            tBox.EnableViewState = true;
            ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(tBox);
            //tBox.CheckedChanged += new EventHandler(Force_Post_Back);
        }

        QuickFilter.Attributes["class"] = "quick-filter";
        QuickFilter.Attributes["title"] = "Quick Filter";

        IconMagnifier.Attributes["class"] = "icon-magnifier";

        GridResults.ID = "ltlGridResults";
        GridResults.ClientIDMode = ClientIDMode.Static;
        //GridResults.EnableViewState = false;

        QuickFilter.Controls.Add(IconMagnifier);

        GridHeader.Controls.AddAt(0, tBox);
        GridHeader.Controls.Add(QuickFilter);
        GridHeader.Controls.Add(GridCount);
        GridHeader.Controls.Add(GridDescription);

        GridItem.Controls.Add(GridHeader);
        GridItem.Controls.Add(GridResults);
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        CreateGrid();
    }

    protected override void Render(HtmlTextWriter writer)

    {
        GridItem.RenderControl(writer);
    }

Image to generated html


Solution

  • I added the following line of code to the bottom of my CreateGrid method:

    this.Controls.Add(GridItem);
    

    This allowed me to add the GridItem control to the current control, thus allowing for post backs. Without this call even though you render the Checkbox, it is completely dumb.