C# – Problems with asp:Button OnClick event

asp.netc++onclick

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?

Best Solution

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.

Related Question