H...">

Asp issues: Button OnClick event

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 an 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?

+3
source share
4 answers

There are two problems here. Firstly, the onclick event has a specific signature.

MethodName(object sender, EventArgs e);

Secondly, in the markup, you need to pass the method name only without parentheses or parameters.

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

Then change your code as follows:

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

Parameters can be passed on the client-side click event handler, in this case OnClientClick, but not on the server-side handler.

+16

OnClick - . eventHandler, , EventHandler, . OnClick void doSomething(object sender, EventArgs e). , .

, . manuplation, , - .

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

public void doSomething(object sender, EventArgs e)
{
int AnotherNumber=   Int32.Parse(txtNumber.Text)+10;
}
+2

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

and to pass parameters you need work like this:

for example, if you can specify your parameter in the attribute value in the Html control (for example, the ID in this exapmle), and then get it in the server-side handler

To make a style color change control

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("");
}

etc.

0
source

Source: https://habr.com/ru/post/1710651/


All Articles