A newby question. Please help

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,
The problem is laughably simple: I have a text box which must accept only
numbers (on aim to restrict some extremely "talented" users to write, for
example "blahblahblah" instead of 234); In C++ that is not a problem. As soon
as you link some variable with dialog item, for example link a text box with
some integer, the compiler restricts user to enter any char in above box,
except numeric. in more subtle cases, one may use IsAlpha, IsAlnim and other
functions to make decision.
I am new to C# and still can not find the easy way. The only way I managed
to find, is to override OnKeyDown function, check character by myself and
allow only right ones.
Can anybody tell an easier way?
 
This is the way to do it if you want the user to experience nothing but
digits typing in the text box.

Or you can allow the user to type anything they want but then use the
Validating event to warn them of bad content. It all depends upon the
user experience you want to offer.

If you're going to do it using OnKeyDown, then just create a subclass
of TextBox called, say, TextBoxNumeric, and then drop that on your
form. Then you can reuse it.

I think that we're all gradually building libraries of special-purpose
input controls, that we may all soon throw away, becuase I believe that
the 2.0 .NET framework includes a text box with an input mask property,
so that you can specify in mask form what the text box should accept.
 
You're on the right track if this is really what you need to do. But if I
were you, I'd ask myself if maybe I wanted to use a NumericUpDown control
rather than a TextBox control. If you really just need numbers, you're
going to an awful lot of extra trouble...
 
I will not recommend stopping the characters entering, I would rather
validate it to be a number and show the little error provider error if
invalid. If you want your numeric textbox... apart from the things mentioned
by others, you will also need to override the default context menu (and Ctrl
+ V) to stop people pasting text into it. I have seen people override the
context menu by creating the new contextmenu without any entries. This gets
rid of the copy context menu as well which is quite annoying.
 
Back
Top