Casting

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

rn5a

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

JosephByrns

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.
 
R

rn5a

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

Joseph Byrns

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"))
 
F

Flinky Wisty Pomm

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top