FindControl() return null

自作多情 提交于 2019-11-29 15:08:18
StuartLC

FindControl only searches direct children of the container. Since you are starting off at the page level, you will need to recurse through the child UpdatePanel control to get to your btnAdd control.

Have a look here for an example how to do do this.

Edit: I'm not sure I understand why you are 'looking' for your button in this manner, since there is only one static button on the screen - you wouldn't need to use FindControl in this case.

<asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" />

(or in code, btnAdd.OnClick += new EventHandler(btnAdd_Click);)

Even if you had multiple Buttons in your form added dynamically, you could wire ALL of them up to the same Button Click handler, in which case sender would then contain the Button Control which was clicked. You would typically use FindControl to scrape the data out of the dynamically added Input controls (text box etc), rather than to see which control caused the Postback (as 'sender' in an appropriate event handler would be easier)

Edit 2: You can add the buttons dynamically just like your other controls

    Button myButton = new Button();
    myButton.Text = "Click Me";
    myButton.Click += new EventHandler(btnAdd_Click);
    myPlaceHolder.Controls.Add(myButton); 

If you want all the controls that you've added already to 'stay' in between postbacks then enable viewstate on the page and on the controls, and then make sure that you only add the controls once without postback, in OnInit:

   base.OnInit(e);    
   if (!IsPostBack)
   { // ... Add controls here

You can keep the state of 'mycount' in a hidden field (in the same updatepanel, and with viewstate enabled) - you'll need to parse it to an int each time. Or you can use SessionState to track it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!