Frage

In my User Control I have a Text Box which does the validation to take only digits. I place this user control on my form but the Keypress event is not Firing in form.Following is the code in my user control

    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        base.OnKeyPress(e);
        if (this.KeyPress != null)
            this.KeyPress(this, e);
    }
 private void txtLocl_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar!=(char)Keys.Back)
        {
            if (!char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }
    }

but in Form also i want keypress event to fire but it is not firing

public Form1()
    {
        InitializeComponent();
        txtNum.KeyPress += new KeyPressEventHandler(txtPrprCase1_KeyPress);
    }

    void txtPrprCase1_KeyPress(object sender, KeyPressEventArgs e)
    {
        MessageBox.Show("KeyPress is fired");
    }

but it is not firing. I don't understand what i want to do? It is Urgent for me.

War es hilfreich?

Lösung

This following override is not needed:

protected override void OnKeyPress(KeyPressEventArgs e)
{
    base.OnKeyPress(e);
    if (this.KeyPress != null)
        this.KeyPress(this, e);
}

Because base.OnKeyPress(e); will fire the attached event. You don't need to do it manually.

Instead call OnKeyPress of user control in the text-box's event handler:

private void txtLocl_KeyPress(object sender, KeyPressEventArgs e)
{
    base.OnKeyPress(e);

    if (e.KeyChar!=(char)Keys.Back)
    {
        if (!char.IsDigit(e.KeyChar))
        {
            e.Handled = true;
        }
    }
}

Andere Tipps

Try putting the event handler code in your Form_Load event, or using the Form Designer to create the event handler (it's in the lightning icon on the properties page).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top