ASP .NET Button event handlers do not fire on the first click, but on the second click after a PostBack

后端 未结 8 2047
Happy的楠姐
Happy的楠姐 2020-12-02 17:02

Background: I am customizing an existing ASP .NET / C# application. It has it\'s own little \"framework\" and conventions for developers to follow when exte

相关标签:
8条回答
  • 2020-12-02 17:35

    I had the same problem, but the accepted answer here was not causing it. I had a text box and a search button, and clicking the button the first time didn't perform the search. The event handler of the button wasn't being hit. But clicking the button a second time did trigger the event on the server. Here is why:

    If you have an <asp:Textbox> with its AutoPostBack set to true, after typing in the text box and then moving to click a button, the text box causes a post-back immediately the moment it loses focus. So the click even of the button doesn't count (the page is already posted-back as a result of the text box's event). That's why when you click the button a second time, it works because the text box is not involved in the second post-back.

    Set the AutoPostBackproperty of the <asp:Textbox> to false to fix this issue.

    0 讨论(0)
  • 2020-12-02 17:44

    A quick fix is to set an ID to the ASCX control your are loading on a page. For example, if your code is like this:

            UserControl SpecsControl = (UserControl)Page.LoadControl("../name.ascx");
            SpecsContainer.Controls.Add(SpecsControl);
    

    then you need to add a line (before Controls.Add):

                SpecsControl.ID = "Aribtrary_Name";
    

    Then your handler method is fired at the first click.

    0 讨论(0)
提交回复
热议问题