Dynamically generated Controls ID returned as NULL

2019-07-23 08:49发布

问题:

I am able to create dynamic controls in Page_PreInit() function.

'How to retrieve the control and its ID'

My C# code to create one of the DynamicControls

 var btn = new WebForms.Button();
        btn.Text = "+";
        btn.ID = "Addmore";
        btn.Click += new System.EventHandler(AddMoreSearchFields);

I am using the below piece of code to find which controlid is clicked.

string eTarget = Request.Params["__EVENTTARGET"].ToString();

**eTarget is always "" NULL**

protected void Page_PreInit(object sender, EventArgs e)
    {

        if (Page.IsPostBack)
        {
            createdynamiccontrols(dynamic_filter_table.Rows.Count);

            string eTarget = Request.Params["__EVENTTARGET"].ToString();


            if (eTarget == "")
            {
                createdynamiccontrols(dynamic_filter_table.Rows.Count);

            }

        }

    }

回答1:

Where's the code where you actually add the button to the page?

Also, it would probably be easier to just add the button to the page - not dynamically - and than arrange visibility based on what you need.

Maybe you even have added the button to the page not dynamically and forgot to set the runat="server" attribute?