Problems with asp:Button OnClick event

2019-05-15 23:53发布

问题:

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?

回答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.



回答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



回答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;
}


回答4:

You Must Change your Method's Structure to be like

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

and for passing parameters you need a work around like this :

for example if you in an Html control you may but your parameter in an attribute value (such as ID in this exapmle) and then retrieve it in the server side handler

i.e to make an control changing the style color

Html :

<a href="" id="Grey" runat="server" onserverclick='ApplyStyleEvent'></a>

Code :

protected void ApplyStyleEvent(object sender, EventArgs e)
{
    Profile["SelectedStyle"] = ((HtmlControl)sender).ID;
    Response.Redirect("");
}

and so on.