Problems with asp:Button OnClick event

46,547

Solution 1

There are two problems here. First, the onclick event has a specific signature. It is

MethodName(object sender, EventArgs e);

Second, in the markup, you need to pass the Method name only with no parentheses or params.

<asp:Button ID="myButton" Text="Click Me" OnClick="doSomething" runat="server" />

Then change your codebehind as follows:

public void doSomething(object sender, EventArgs e)
{
    ....
}

The passing of parameters can done on a client side click event handler, in this case OnClientClick, but not on the server side handler.

Solution 2

There is simpler solution. You could use ASP button OnCommand event. More about here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.oncommand.aspx

Solution 3

OnClick of the Button is an Event Handler. To hook a function to an eventHandler you need to obey the Contract that was defined by the EventHandler, as mentioned by Jose. OnClick is bound to a function of the format void doSomething(object sender, EventArgs e). So your function should be of the same format.

I am unsure why would want to pass a parameter to the Event Handler. If you want to take some manuplation you need to do that using some other control.

<asp:TextBox ID="txtNumber" runat="server" /><asp:Button ID="myButton" Text="Click Me" OnClick="doSomething" runat="server" />

And in the Code

public void doSomething(object sender, EventArgs e)
{
int AnotherNumber=   Int32.Parse(txtNumber.Text)+10;
}
Share:
46,547
Matt
Author by

Matt

Updated on May 27, 2020

Comments

  • Matt
    Matt almost 4 years

    Here is my button

    <asp:Button ID="myButton" Text="Click Me" OnClick="doSomething(10)" runat="server" />
    

    Here is the server function

    public void doSomething(int num)
    {
        int someOtherNum = 10 + num;
    }
    

    When I try to compile the code I get the error "Method Name Expected" for the line:

    <asp:Button ID="myButton" Text="Click Me" OnClick="doSomething(10)" runat="server" />
    

    What am I doing wrong? Am I not allowed to pass values to the server from an OnClick event?

  • Matt
    Matt almost 15 years
    So there's absolutely no way to pass that method a number as long as it's a server side method?
  • Jose Basilio
    Jose Basilio almost 15 years
    That's correct. You can however, read values from other input fields like textboxes or even hidden controls from inside your event handler and use that for your input calculations.