17

I'm trying to pass a parameter into a function onClick of an asp:Button

    <asp:Button name='ProductID' onclick="confirm_product_Click" ID="confirmitem" runat="server" Text="accept">

the parameter is <%=product.ProductId %>.

I cant use CommandArguments because the value is passed like plain text.

I tried with hidden input but it failed.

I also tried using form action:

<form method="post" action="?ProductID=<%=product.ProductId %>"> 
<asp:Button name='ProductID' onclick="confirm_product_Click" ID="confirmitem" runat="server" Text="accept">
</form>

but it doesn't send the value to the function. Can someone help me solve this problem?

rogerdeuce
  • 1,471
  • 6
  • 31
  • 48
Yanay Hollander
  • 327
  • 1
  • 5
  • 19

2 Answers2

38

in your aspx

<asp:Button ID="test" runat="server" CommandArgument='<%#Eval("product.ProductId")%>' CommandName="ThisBtnClick" OnClick="MyBtnHandler" />

in code behind

void MyBtnHandler(Object sender, EventArgs e)
{
   Button btn = (Button)sender;
   switch (btn.CommandName)
   {
      case "ThisBtnClick":
         DoWhatever(btn.CommandArgument.ToString());
         break;
      case "ThatBtnClick":
         DoSomethingElse(btn.CommandArgument.ToString());
         break;
   }
}
Icculus018
  • 1,018
  • 11
  • 19
Zohaib Waqar
  • 1,204
  • 11
  • 18
0

If it is a LinkButton...

<asp:LinkButton ID="test" runat="server" CommandArgument='<%#Eval("product.ProductId")%>' OnClick="MyBtnHandler" /> 

 protected void MyBtnHandler(object sender, EventArgs e)
        {
         
string ProductID = ((LinkButton)sender).CommandArgument.ToString();
...
}
Stephan Vierkant
  • 9,674
  • 8
  • 61
  • 97