user1457613
user1457613

Reputation: 115

ASP.NET Add Command Argument to Button in Code Behind

I am trying to grab an argument added to an asp:button in code behind, but getting error:

Unable to cast object of type 'System.EventArgs' to type 'System.Web.UI.WebControls.CommandEventArgs'

This button is part of a normal form, not a gridview, etc..

What might I be doing wrong? Regards.

<form><asp:Button ID="btnPrint" runat="server" Text="Print" CommandArgument="" /></form>

Imports System.Web

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim String AS String = "MyValue"
    btnPrint.CommandArgument = String

End Sub    

Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As CommandEventArgs) Handles btnPrint.Click


     Dim ID as String = e.CommandArgument.toString

     'Have also tried
      'Dim btn As Button = sender
      'Dim ID As String = btn.CommandArgument

      Response.Redirect("Print.aspx?tid=" & ID)

End Sub

Upvotes: 1

Views: 3441

Answers (2)

Steve
Steve

Reputation: 5545

My ASP button click events look like this:

Private Sub SearchASPxButton_Click(sender As Object, e As EventArgs) Handles SearchASPxButton.Click

Notice the second parameter is of type System.EventArgs. Did you change the type of the automatically generated click event? Or did you create this manually yourself?

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102763

You just need to update btnPrint_Click to handle the Command event instead of "Click":

Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As CommandEventArgs) Handles btnPrint.Command

Upvotes: 2

Related Questions