Casting

  • Thread starter Thread starter rn5a
  • Start date Start date
R

rn5a

Can System.EventArgs be cast to CommandEventArgs? If so, how?

Actually I want the Page_Load sub to invoke another sub which is the
OnCommand event handler of a LinkButton.

<script runat="server">
Sub Page_Load(obj As Object, ea As EventArgs)
CallCmd(obj, ??)
End Sub

Sub CallCmd(obj As Object, ea As CommandEventArgs)
..........
..........
End Sub
</script>
<form runat="server">
<asp:LinkButton ID="lnkButton" OnCommand="CallCmd" Text="ABCD"
runat="server"/>
</form>

For the Page_Load sub to invoke CallCmd, the second parameter should be
of type CommandEventArgs. How do I cast EventArgs to CommandEventArgs?
 
Joseph, I am getting the following error:

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

pointing to the line

CallCmd(obj, CommandEventArgs.Empty)

Any other suggestions?
 
Hmmm, I tried it got the same error, I have no idea why that happens, but if
you try:

CallCmd(obj, Nothing)

instead, then it will work.
 
Yeah Joseph that works but the problem is I am using the
CommandArgument property of the LinkButton (sorry, I should have
mentioned this before)

<asp:LinkButton ID="lnkButton" OnCommand="CallCmd"
CommandArgument="Col1" Text="ABCD" runat="server"/>

The CallCmd sub looks like this:

Sub CallCmd(obj As Object, ea As CommandEventArgs)
txtCall.Text = ea.CommandArgument
..........
..........
End Sub

Now when I invoke CallCmd from Page_Load using

CallCmd(obj, Nothing)

then ASP.NET generates the following error:

Object reference not set to an instance of an object.

pointing to the first line shown above in the sub CallCmd!

Any other ideas??
 
You could either check to see if it is nothing before you use ea or you
could call it like:

CallCmd(Me, New CommandEventArgs("Command From Load", "LoadArgument1"))
 
Better yet, refactor your event handler to pass its work on to another
method

Sub CallCmd(sender as Object, e as CommandEventArgs)
DoSomethingWithCmd(e.CommandArgument)
End Sub

Sub DoSomethingWithCmd(argument as string)
...
End Sub


Sub Page_Load(sender as object, e as EventArgs)

...
DoSomethingWithCmd(somePredefinedString)
...
End Sub



Generally, you'll find your life easier if Event Handlers do _nothing_
but handle an event. The actual work should be done in a different
method for precisely this reason.
 
Back
Top