简体   繁体   中英

cannot assign because it is a method group

I Show and Hide my user controls in one of the usercontrols I have another one I want when the main usercontrol Show,the other usercontrol hide.

I get this when I want to add visible function for usercontrol

private void AddVisibleChangedEventHandler()
{
        this.VisibleChanged += new EventHandler(VisibleChanged);
}

private void VisibleChanged(object sender, EventArgs e)
{
        MessageBox.Show("Visible change event raised!!!");
}

You need to have an event declared in your class like this:

public event EventHandler ExampleEvent;

and then you need to associate a method delegate to that event, turning that method/delegate into the event handler.

this.ExampleEvent+= this.ExampleEventHandlerClassMethod;

or a static method

this.ExampleEvent += ExampleClass.ExampleStaticEventHandler;

Your example looks very brief, but it looks like that class either has an event called VisibleChanged or your declaring a method called Visible Changed and then trying to assign that method to handle itself, which doesn't make sense.

If you already have the event, then you should try changing your method name that you want to use to handle that event to something like VisibleChangedHandler and then do this.VisibleChanged += this.VisibleChangedHandler;

This looks relevant: Cannot Assign because it is a method group C#?

And this: https://docs.microsoft.com/en-us/dotnet/standard/events/

Rename your event handler function. You have declared a method with the name VisibleChanged . This name is already defined as an event in UserControl . Name your method anything else and it will start working correctly. For example:

private void AddVisibleChangedEventHandler()
{
    this.VisibleChanged += MyVisibleChangedHandler;
}

private void MyVisibleChangedHandler(object sender, EventArgs e)
{
    MessageBox.Show("Visible change event raised!!!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM