1

I have created dynamic controls on DropdownList's SelectedIndexChanged event. Button is one of those controls. I have also assigned event to that button but debugger is not coming on that click event. Following is my code.

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            token = Session["LoginToken"].ToString();
            if (!IsPostBack)
            {
                BindData();
                fsSearch.Visible = false;
                btnDownload.Visible = false;
            }
            else
            {
                foreach (HtmlTableRow row in (HtmlTableRowCollection)Session["dynamicControls"])
                {
                    tblSearch.Rows.Add(row);
                }
            }
        }
        catch
        {
        }
    }

    private void BindData()
    {
        ddlReportName.DataSource = svcCommon.GetReports(token, out message);
        ddlReportName.DataValueField = "Key";
        ddlReportName.DataTextField = "Value";
        ddlReportName.DataBind();
        ddlReportName.Items.Insert(0, "--Select--");
    }

    protected void ddlReportName_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            string[] reportInfo = ddlReportName.SelectedValue.Split('|');

            Session["dynamicControls"] = null;
            tblSearch.Rows.Clear();

            HtmlTableRow row = new HtmlTableRow();
            HtmlTableCell cellFieldNameLbl = new HtmlTableCell();
            HtmlTableCell cellFieldNameDdl = new HtmlTableCell();
            HtmlTableCell cellOperatorLbl = new HtmlTableCell();
            HtmlTableCell cellOperatorDdl = new HtmlTableCell();
            HtmlTableCell cellValueLbl = new HtmlTableCell();
            HtmlTableCell cellValueTxt = new HtmlTableCell();
            HtmlTableCell cellOperatorRbtn = new HtmlTableCell();
            HtmlTableCell cellAddMoreFilter = new HtmlTableCell();
            Button btnAddMore = new Button();

            DropDownList ddlColumn = new DropDownList();
            DropDownList ddlOperator = new DropDownList();
            TextBox txtValue = new TextBox();
            RadioButtonList rbtnOperator = new RadioButtonList();

            List<string> filterValues = svcCommon.GetSearchColumns(Convert.ToInt64(reportInfo[0]), token, out message);

            fsSearch.Visible = btnDownload.Visible = filterValues.Count > 0 ? true : false;

            ddlColumn.ID = "_ddlColumn0";
            ddlOperator.ID = "_ddlOperator0";
            txtValue.ID = "_txtValue0";
            rbtnOperator.ID = "_rbtnOperator0";
            btnAddMore.ID = "_btnAddMore0";


            rbtnOperator.Items.Add("AND");
            rbtnOperator.Items.Add("OR");
            rbtnOperator.RepeatDirection = RepeatDirection.Horizontal;

            btnAddMore.Text = "Add More";

            btnAddMore.Click +=btnAddMore_Click;

            ddlColumn.DataSource = filterValues;
            ddlColumn.DataBind();

            ddlOperator.DataSource = new List<string>() 
                                        {   
                                            "Equal",
                                            "Not Equal",
                                            "Less Than",
                                            "Less Than Or Equal",
                                            "Greater Than",
                                            "Greater Than Or Equal",
                                            "Start With",
                                            "Not Start With",
                                            "End With",
                                            "Not End With",
                                            "Contains",
                                            "Not Contains",
                                            "Between",
                                            "Not Between",
                                            "In",
                                            "Not In"
                                        };
            ddlOperator.DataBind();

            cellFieldNameLbl.InnerText = "Field Name:";
            cellFieldNameDdl.Controls.Add(ddlColumn);
            cellOperatorLbl.InnerText = "Operator";
            cellOperatorDdl.Controls.Add(ddlOperator);
            cellValueLbl.InnerText = "Value";
            cellValueTxt.Controls.Add(txtValue);
            cellOperatorRbtn.Controls.Add(rbtnOperator);
            cellAddMoreFilter.Controls.Add(btnAddMore);

            row.Cells.Add(cellFieldNameLbl);
            row.Cells.Add(cellFieldNameDdl);
            row.Cells.Add(cellOperatorLbl);
            row.Cells.Add(cellOperatorDdl);
            row.Cells.Add(cellValueLbl);
            row.Cells.Add(cellValueTxt);
            row.Cells.Add(cellOperatorRbtn);
            row.Cells.Add(cellAddMoreFilter);

            tblSearch.Rows.Add(row);
            Session["dynamicControls"] = tblSearch.Rows;
        }
        catch (Exception ex)
        {
        }
    }

    protected void btnAddMore_Click(object sender, EventArgs e)
    {
        try
        {

        }
        catch
        {
        }
    }
Imad
  • 7,126
  • 12
  • 55
  • 112

2 Answers2

3

The problem with dynamically created controls in asp.net webforms is that they aren't automatically added to the viewstate, so the postback event won't happen.

This should help you to understand adding controls dynamically, and managing them via the viewstate http://forums.asp.net/t/1900207.aspx?Creating+buttons+dynamically

Alternatively, a much easier way to manage this is to have the buttons on the page but not visible, then in the selected_index_changed event, just switch the visibility to true.

Adam Drew
  • 155
  • 8
  • both the alternatives cant work because problem is not with view state, second i dont know number of control that will be created at design time. – Imad Aug 03 '15 at 13:25
  • I think your problem IS in your view state. Easiest way around this is probably to throw your dynamic content into a [UpdatePanel](https://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1) – Christopher Aug 03 '15 at 13:32
  • I agree that the problem isn't with the viewstate, it's that controls added dynamically aren't in the viewstate, so in the page load cycle, when it get's round to checking if there are any events bound to controls to fire, it won't find them, because they aren't there. The only way round this, if they **really** have to be fully dynamic, is to add them back into the viewstate in the page load or init page cycle events. Here's another example of how this is acheived: http://www.codeproject.com/Articles/3684/Retaining-State-for-Dynamically-Created-Controls-i – Adam Drew Aug 03 '15 at 16:02
  • Also, a quick search on SO yielded this http://stackoverflow.com/questions/7164628/dynamically-created-button-click-event-not-firing?rq=1 so I think this is a duplicate. On this question Achim points out what I'm trying to say in a much better way, but the general consensus is that you should be toggling visibility, rather than creating controls – Adam Drew Aug 03 '15 at 16:13
0

I hadn't enough time to try so many thing. The thing I did is stored the container on which dynamic controls are added into Session and on Page_Init event I have bound event and it is working fine now. :)

Imad
  • 7,126
  • 12
  • 55
  • 112