-2

I have a code that only allows numbers, comma and backspace to be entered in a textbox. But at the same time, I cannot insert text via ctrl + v. How can I do this?

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            char number = e.KeyChar;
            if ((e.KeyChar <= 47 || e.KeyChar >= 58) && number != 8 && number != 44)
            {
                e.Handled = true;
            }
        }
  • Does this answer your question? [Handle a paste event in c#](https://stackoverflow.com/questions/15987712/handle-a-paste-event-in-c-sharp). Also, have you [read](https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.textbox.paste?view=winrt-19041) the documents? – Trevor Apr 20 '21 at 20:22
  • Does this answer your question? [C# check characters in clipboard when paste into textbox](https://stackoverflow.com/questions/32730131/c-sharp-check-characters-in-clipboard-when-paste-into-textbox) – Charlieface Apr 20 '21 at 21:17
  • Build a Custom Control derived from TextBox, override CreateParams and add to the Styles [ES_NUMBER](https://learn.microsoft.com/en-us/windows/win32/controls/edit-control-styles): now the TextBox only accepts numbers (and you can only paste in numbers). – Jimi Apr 21 '21 at 01:08

1 Answers1

0

Considering that you are not checking e.Control property you are handling Ctrl+V in this event. e.Handled = !e.Control; will fix your code. Of course this will not prevent users from pasting in not numeric text. Probably better to handle OnTextChanged event and prevent entry that way.