tags:

views:

831

answers:

3

I have a button on my MasterPage and I want the ContentPage to handle the Click event of the button. Here's what I have so far:

//Event in MasterPage
public event EventHandler Search_Submit;

//ButtonClick event in MasterPage
protected void SearchButton_Click(object sender, EventArgs e)
    {
        if (Search_Submit != null)
        {               
            Search_Submit(this, EventArgs.Empty);
        }
    }


//EventHandler in Page_Init on ContentPage
Master.Search_Submit += new EventHandler(Master_Search_Submit);

//Search_Submit event in ContentPage
private void Master_Search_Submit(object sender, EventArgs e)
    {
        //Perform appropriate action...
    }

This all works - however, I would like to pass a value with the EventArgs. I believe I need to create a custom EventArgs class that inherits from EventArgs and has my custom properties. However, my when I do that I get the following error: No overload for 'Master_Search_Submit' matches delegate 'System.EventHandler'.

+1  A: 

You have defined your event to use the EventHandler delegate. A delegate is a pointer to a function, it defines the signature the responding method must have. The signature for the EventHandler delegate is:

delegate void EventHandler(object sender, EventArgs e);

In .NET 2.0 there is a generic EventHandler delegate that allows you to specify the EventArgs type you would like to use.

public event EventHandler<MyEventArgs> Search_Submit;

Now you can use an event handler with the signature

void EventArgs<TArgs>(object sender, TArgs e) where TArgs: EventArgs

In your case this would be:

void Master_Search_Submit(object sender, MyEventArgs e)
NerdFury
I have changed my event declaration like you mention, and changed my event handler to use my custom EventArgs class. However, I am still getting the same error with the line in the Page_Init class (see original post for code).
Mike C.
I changed that line to Master.Search_Submit += new EventHandler<SearchEventArgs>(Master_Search_Submit); and it worked properly. Thanks!!
Mike C.
+1  A: 

Either you'll have to pass the your arguments as an EventArgs, and cast it in your handler:

private void Master_Search_Submit(object sender, EventArgs e)
{

    MyEventArgs mea = (MyEventArgs)e;
    //Perform appropriate action...
}

Or you'll have to define a delegate that expects your custom event args class:

 public delegate void MyEventHandler(object sender, MyEventArgs mae);
 public event MyEvent myEvent

 myEvent += new MyEventHandler(Master_Search_Submit);
A: 

You can use CommandEventHandler instead of EventHandler delegate.

odiseh