tags:

views:

258

answers:

3

I can easily understand how to use custom events in pure C# code, but how can I do pass in custom event arguments on asp:button click?

I've tried all sorts of things (defining new event args, new delegates, etc etc) but I have had no luck.

Is there a tutorial of how to do this with the standard asp controls?

+2  A: 

As long as your EventArgs inherit from System.EventArgs you will be able to pass them. Then, once inside your event handler, you can cast the event to the proper subtype.

Here is an example:

using System;

class Program
{
    static event EventHandler Foo;

    static void Main()
    {
     // Here is cast the EventArgs to FooEventArgs
     Foo += (o,e) => Console.WriteLine(((FooEventArgs)e).Number);

     // Notice that I am passing a "FooEventArgs" instance
     // even though the delegate signature for "EventHandler"
     // specifies "EventArgs".  Polymorphism in action. :)
     Foo(null, new FooEventArgs { Number = 1 });
    }
}

class FooEventArgs : EventArgs
{
    public int Number { get; set; }
}

I know that you are working with existing control delegates so unfortunately this kind of casting is neccessary. Keep in mind though that there is a EventHandler<T> where T : EventArgs delegate in .NET 2.0 and greater that will allow you to do what I have done above without casting.

Andrew Hare
I did get some issue about the compatibility between eventargs and my customeventargs. I guess casting could solve that. I'll give that a try :)
dotnetdev
+1  A: 

I don't believe there is a way to do this without creating your own controls. However, I sometimes use the commandagument and commandname properties on a button to provide additional information

Jeremy
A: 

I don't thinks you can. The Button itself will be calling the Click event with it's own EventArgs object, and unfortunately you can't hijack that call. You can however use closures:

protected void Page_Load(object sender, EventArgs e)
{
    int number = 1;
    button.Click += (o, args) => Response.Write("Expression:"+number++);
    number = 10;
    button.Click += delegate(object o, EventArgs args) {  Response.Write("Anonymous:"+number); };
}

By the way the output for this is

Expression:10Anonymous:11
Understanding why this is the output is a big step into understanding closures! Even though number is out of scope when Click Event is handled, it is not destroyed because both of the defined event handler's have references to the it. So it and it's value will be maintained until it is no longer needed. I know that's not the most technical explanation of closures, but should give you an idea of what they are.

Josh