Skip to content Skip to sidebar Skip to footer

Method Being Triggered On Page Load But Not Via Asp Button

I have two asp:Labels, the first of which is replaced with a few buttons and the second with a list of items. I want to click on the buttons to filter the items. The contents of th

Solution 1:

The OnClientClick property specifies the javascript to run in the browser when the button is clicked. Since you probably don't have a javascript function called Load_Items, this will generate a script error, and the button will then cause the form to post back.

The server-side Click event will fire on the server, but doesn't allow you to pass a parameter. You will only get the button instance and an empty EventArgs instance.

You might be better off using the Command event, combined with the CommandArgument property.

<asp:Button runat="server" CommandArgument="2" OnCommand="Load_Items" ...

The event handler would use the CommandArgument property of the CommandEventArgs to access the argument from the clicked button:

protectedvoidLoad_Items(object sender, CommandEventArgs e)
{
    Load_Items(Convert.ToInt32(e.CommandArgument));
}

Solution 2:

Well, that's the common problem which I think every asp.net developer deals some time. The common part of it, that asp.net event system doesn't work, as windows forms. Page object, and all controls on that page, have lifecycle events, that are triggered during any request, even when it's from update panel. As you create those controls by code, you have to keep in mind, that all events for those controls should work as part of Page object. That's why you have to create those object in Page_Init event, before all other control's event would be triggered. Please also keep in mind that you have to create those controls as asp.net objects:

var btn = new Button();

But not by simply adding html markup. And you have to recreate them on each request, following that one, when they were created.

Please take a look on my another answer.

Post a Comment for "Method Being Triggered On Page Load But Not Via Asp Button"