Blocking Letters or Numbers in a TextBox

Ensuring Only Numbers are Entered in the TextBox

In some programs we write, we require the user to enter numbers in the text box to perform numerical operations. We can easily understand whether the user left the box empty with the if structure.

However, if the user enters letters or other characters instead of numbers in the box, this will also cause an error. We can take various measures to prevent this.

In the example below, keys other than numeric keys are disabled, thanks to the codes written for the KeyPress (key press) event of the textBox1 object.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}

* If the same control is to be made for more than one text box, we do not need to rewrite the same program for each one. We can write the name of the created program against the KeyPress event of all text boxes.

** This method is not a solution to the copy paste event. The user can still cause an error by pasting the copied text into the text box.

It is very simple to block shortcut keys such as copy-cut-paste in the text box. Simply set the ShortcutsEnabled property of the corresponding text box to false.

Ensuring Only Letters in the Text Box

We can use the following codes to prevent entering a character other than a letter in the text box at the time of the event.
 
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
      e.Handled = !char.IsLetter(e.KeyChar);
}
Blocking letters in textbox, entering only numbers in textbox, blocking copy-paste in textbox, ShortcutsEnabled feature

EXERCISES

There are no examples related to this subject.



COMMENTS




Read 569 times.

Online Users: 3



blocking-letters-in-a-textbox