tags:

views:

402

answers:

6

Hello,

I created an OnPaint event of my button,which I lately tried to override,but I failed

My code:

    protected override void button1_Paint(PaintEventArgs e)
    {
    }

I get this error: "no suitable method found to override".

What should I do to make the error dissapear,but keep the method as override?

+1  A: 

In your base-class, you need to declare the method as virtual

example:

public class Person
{
    public virtual void DoSomething()
    {
        // do something here
    }
}

public class Employee : Person
{
    public override void DoSomething()
    {
        base.DoSomething();
    }
}

Edit:

Perhaps this can help you out?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
    }

    private void button1_Paint(object sender, PaintEventArgs e)
    {

    }


}
Natrium
This is the base class,its placed in Form1 class and the designer is also inherited from Form1.
John
@John: if it's in the base class, what do you want to override?
Mehrdad Afshari
A: 

You should declare the method in the base class as virtual in order to be able to override it.

Mehrdad Afshari
+3  A: 

If the method is not virtual, you can't override it. If you can't override it, there is no point in trying to keep the override keyword.

If you want to shadow the method, you use the new keyword instead of override.

Guffa
I'm asking,because of the third answer in this question -> http://stackoverflow.com/questions/946150/why-does-text-drawn-on-a-panel-disappear made by BFree.I can't make it override
John
I see. Then you have to create a class that inherits from Panel, so that you can override the OnPaint method.
Guffa
A: 

you override methods coming from other classes. To keep the method you'll have to put it in a child class and call it from there.

do you have the override in the same class as the original method? if so, just merge the functions and remove the override.

Makach
+3  A: 

The method that you want to override is probably called OnPaint, not button1_Paint. Change the method declaration so it looks like this instead:

protected override void OnPaint(PaintEventArgs e) { }

Note though that this code should be in a subclass of the class from which you want to override the method. If you place this method in a form, it will handle that form's painting.

Fredrik Mörk
A: 

I guess you have something like this now:

public class MyButton : Button {
    public MyButton() {
        this.Paint += new PaintEventHandler(MyButton_Paint);
    }

    void MyButton_Paint(object sender, PaintEventArgs e) {
        //your code
    }
}

If you inherited from a button you should use this code:

public class MyButton : Button {
    protected override void OnPaint(PaintEventArgs pevent) {
        base.OnPaint(pevent);
    }
}
Stormenet