Your approach would almost work, but you also need to check up present number of characters of the text box. You can type-case the parameter
sender
to
TextBox
and checkup
TexBoxBase.TextLength
. If the character is not backspace, and you have maximum number of characters already, assign
e.Handled = true;
that's all.
However,
there is absolutely no need to do anything like that. It is already done for you. All you need is to assign the maximum number of characters to the property
TextBoxBase.MaxLength
:
TextBoxBase.MaxLength Property (System.Windows.Forms)[
^].
Problem solved.
Now, the advice not related to your functionality, only to the code style, maintainability and the way you ask questions. First, never use auto-generated names like
textBox1_KeyPress
, by obvious reasons. The are not supposed to be used permanently. They violate (good) naming conventions. You are given Intellisense to rename them. The names should be semantically sensible. Moreover, even if the name suggests that this is an event handler, there is no evidence that it is. This is just a method. It because a handler if the operator += is performed on some event instance. Therefore, you need to show it. By a number of reasons, I avoid adding any event handlers via the designer and strongly advise the same to everyone.