Search code examples
c#winformsuser-controlsoverriding

Override TextChanged event for a custom control not working


I tried this code in my custom user control in a C# Windows application:

public partial class HtextBox : DevExpress.XtraEditors.TextEdit
{
    protected override void OnTextChanged(KeyEventArgs kpe)
    {
        if (kpe.KeyCode == Keys.D1 ||
            kpe.KeyCode == Keys.D2 ||
            kpe.KeyCode == Keys.D3 ||
            kpe.KeyCode == Keys.D4 ||
            kpe.KeyCode == Keys.D5 ||
            kpe.KeyCode == Keys.D6 ||
            kpe.KeyCode == Keys.D7 ||
            kpe.KeyCode == Keys.D8 ||
            kpe.KeyCode == Keys.D9 ||
            kpe.KeyCode == Keys.D0
            ) {
                base.Text += kpe.KeyValue;
        }
    }
}

I got this error:

Error 1 'myproject.HtextBox.OnTextChanged(object, System.Windows.Forms.KeyEventArgs)': no suitable method found to override E:\my project\myproject\HtextBox.cs

I want create a custom textbox. Here I want this textbox just to get numbers as input. What would an example be?


Solution

  • Even though KeyEventArgs is a subclass of System.EventArgs, C# does not let you override a method with a subclass parameter. You need to override the method with the signature from the base class, and then cast to KeyEventArgs inside your function:

    protected override void OnTextChanged(System.EventArgs args) {
        KeyEventArgs kpe = (KeyEventArgs)args;
        ...
    }
    

    Edit: Since OnTextChanged does not provide KeyEventArgs and it looks like you need them, try overriding a different method:

    protected override void OnKeyDown(KeyEventArgs kpe) {
        ...
    }