By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,213 Members | 1,105 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,213 IT Pros & Developers. It's quick & easy.

a few beginner questions

P: n/a
I am just learning to program, and hoping someone can help
me with the following:

for a simple calculator, a string is entered into a text
box ... how do I prevent the user from entering a text
instead of a number, or give an error message?

Also, how can I make the program verify there are two
valid entries in txtBox1 and txtBox2 to then ENABLE the
button operators (ie +, -, /, *).

Thanks for the help.
Nov 20 '05 #1
Share this Question
Share on Google+
27 Replies


P: n/a
1)Private Sub TextBox1_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox1.KeyPress

If e.KeyChar.IsNumber(e.KeyChar) Then
e.Handled = False
Else
e.Handled = True
End If

End Sub
2)

On the TextChanged Event of one text box, call some
function....btnCalculate.Enabled = IsValid(textbox1.text) and
IsValid(textbox2.text) Where isValid is your validation routine.

On the textbox1_TextChanged add a second handles clause.... Handles
textbox1.TextChanged, Handles textBox2.TextChanged.

This will do it for you.

Cheers,

Bill
,
"MHoffman" <mh********@hotmail.com> wrote in message
news:37****************************@phx.gbl...
I am just learning to program, and hoping someone can help
me with the following:

for a simple calculator, a string is entered into a text
box ... how do I prevent the user from entering a text
instead of a number, or give an error message?

Also, how can I make the program verify there are two
valid entries in txtBox1 and txtBox2 to then ENABLE the
button operators (ie +, -, /, *).

Thanks for the help.

Nov 20 '05 #2

P: n/a
Hey, thanks for the help ... do you think you could
explain that to me though real quick? I appreciate to
know how to do it, but I want to learn to so one day I can
be richer than bill gates, (just joking, but you know that
I mean).

Also ... what about Exit Confirmation Box?

if easier, e-mail me @ mh********@hotmail.com

thanks,
meredith
-----Original Message-----
1)Private Sub TextBox1_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox1.KeyPress

If e.KeyChar.IsNumber(e.KeyChar) Then
e.Handled = False
Else
e.Handled = True
End If

End Sub
2)

On the TextChanged Event of one text box, call some
function....btnCalculate.Enabled = IsValid(textbox1.text) andIsValid(textbox2.text) Where isValid is your validation routine.
On the textbox1_TextChanged add a second handles clause.... Handlestextbox1.TextChanged, Handles textBox2.TextChanged.

This will do it for you.

Cheers,

Bill
,
"MHoffman" <mh********@hotmail.com> wrote in message
news:37****************************@phx.gbl...
I am just learning to program, and hoping someone can help me with the following:

for a simple calculator, a string is entered into a text
box ... how do I prevent the user from entering a text
instead of a number, or give an error message?

Also, how can I make the program verify there are two
valid entries in txtBox1 and txtBox2 to then ENABLE the
button operators (ie +, -, /, *).

Thanks for the help.

.

Nov 20 '05 #3

P: n/a
Hi

Lol. I thought it would need explaining. It's not obvious stuff. I'll
explain it all - even the stuff that you know.

1 Private Sub TextBox1_KeyPress _
2 (ByVal sender As Object, _
3 ByVal e As System.Windows.Forms.KeyPressEventArgs) _
4 Handles TextBox1.KeyPress
5 If e.KeyChar.IsNumber(e.KeyChar) Then
6 e.Handled = False
7 Else
8 e.Handled = True
9 End If
10 End Sub

1 The event handler for TextBox1's key presses.
2 sender will be TextBox1 but it is passed as an Object for simplicity
(the compiler's not ours).
3 The information about which key and other stuff is passed in a
special structure.
4 This hooks this routine to TextBox1 for KeyPress events.
5 e.KeyChar is the key that was pressed.
IsNumber tests for a digit key.
6 and 8
When a keyboard event handler returns, the caller can either say
"Oh, you've dealt with the key, I won't take it any further" or it can say
"Ah, you just looked at it but it's up to me to deal with it". In this first
case the key is effectively thrown away. In last case, the key is passed on to
the TextBox.

e.Handled tells the call;er whether the key was handled. So False means it
<wasn't> and the key should be kept and passed to the TextBox. And True means
is <was handled> and should be thrown away.

[I'd prefer it to be 'e.IgnoreKey = True'. That seems much more obvious.]

So putting it all together. If the TextBox receives a key, it will be
ignored unless it's a digit.
Part 2 coming up... :-)

Regards,
Fergus
Nov 20 '05 #4

P: n/a
Hello,

"William Ryan" <do********@comcast.nospam.net> schrieb:
If e.KeyChar.IsNumber(e.KeyChar) Then
Better: 'If Char.IsNumber(e.KeyChar) Then'.
e.Handled = False
Else
e.Handled = True


Shorter:

\\\
e.Handled = Not Char.IsNumber(e.KeyChar)
///

--
Herfried K. Wagner
MVP VB Classic, VB.NET
http://www.mvps.org/dotnet
Nov 20 '05 #5

P: n/a
Can you explain e a bit more, I am not familiar with
that ... and what does handle mean?

greatful for the explanantion though!
-----Original Message-----
Hi

Lol. I thought it would need explaining. It's not obvious stuff. I'llexplain it all - even the stuff that you know.

1 Private Sub TextBox1_KeyPress _
2 (ByVal sender As Object, _
3 ByVal e As System.Windows.Forms.KeyPressEventArgs) _ 4 Handles TextBox1.KeyPress
5 If e.KeyChar.IsNumber(e.KeyChar) Then
6 e.Handled = False
7 Else
8 e.Handled = True
9 End If
10 End Sub

1 The event handler for TextBox1's key presses.
2 sender will be TextBox1 but it is passed as an Object for simplicity(the compiler's not ours).
3 The information about which key and other stuff is passed in aspecial structure.
4 This hooks this routine to TextBox1 for KeyPress events. 5 e.KeyChar is the key that was pressed.
IsNumber tests for a digit key.
6 and 8
When a keyboard event handler returns, the caller can either say"Oh, you've dealt with the key, I won't take it any further" or it can say"Ah, you just looked at it but it's up to me to deal with it". In this firstcase the key is effectively thrown away. In last case, the key is passed on tothe TextBox.

e.Handled tells the call;er whether the key was handled. So False means it<wasn't> and the key should be kept and passed to the TextBox. And True meansis <was handled> and should be thrown away.

[I'd prefer it to be 'e.IgnoreKey = True'. That seems much more obvious.]
So putting it all together. If the TextBox receives a key, it will beignored unless it's a digit.
Part 2 coming up... :-)

Regards,
Fergus
.

Nov 20 '05 #6

P: n/a
Hi Herfried,

Better:

'Ignore the Key if it is not a digit.
e.Handled = Not Char.IsNumber(e.KeyChar)

<My> SCNR! :-))

Regards,
Fergus
Nov 20 '05 #7

P: n/a
Hello,

"Fergus Cooney" <fi******@tesco.net> schrieb:
Better:

'Ignore the Key if it is not a digit.
e.Handled = Not Char.IsNumber(e.KeyChar)


No. No. No.

--
Herfried K. Wagner
MVP VB Classic, VB.NET
http://www.mvps.org/dotnet
Nov 20 '05 #8

P: n/a
Hello,

"MHoffman" <mh********@hotmail.com> schrieb:
Can you explain e a bit more, I am not familiar with
that ... and what does handle mean?


RTFM

Handled Property (.NET Framework Class Library)
http://msdn.microsoft.com/library/en...ndledtopic.asp

--
Herfried K. Wagner
MVP VB Classic, VB.NET
http://www.mvps.org/dotnet
Nov 20 '05 #9

P: n/a
is better or shorter better? my teach said shorter is not
always better

-----Original Message-----
Hello,

"William Ryan" <do********@comcast.nospam.net> schrieb:
If e.KeyChar.IsNumber(e.KeyChar) Then


Better: 'If Char.IsNumber(e.KeyChar) Then'.
e.Handled = False
Else
e.Handled = True


Shorter:

\\\
e.Handled = Not Char.IsNumber(e.KeyChar)
///

--
Herfried K. Wagner
MVP VB Classic, VB.NET
http://www.mvps.org/dotnet
.

Nov 20 '05 #10

P: n/a
Hi Meredith, Herfried,

Nice to know your name, Meredith :-)

Sorry if that was confusing. Shorter is better when you are comfortable
with it. Comments should be used when there is any doubt or when the code does
something techie which doesn't explain what it's doing in conceptual terms.

Handled = False is techie for 'keep the key'
Handled = False is techie for 'throw the key away'.

e.Handled = Not Char.IsNumber(e.KeyChar) is techie for "keep the key only
if it is a digit".

I disaprove of such code when it obscures the meaning. To understand it
you have to do some mental hoop-la before you know which way it jumps. - Ok,
I've got a key and it <is> a number, so <Not that> means it's False, so
Handled = False, now that means I <haven't> dealt with the key so that I <do>
want to keep it. Okay. Glad <that's> clear. Now if it <isn't> a number key
then......

At least with a comment you can know what the code is doing, even if
checking it <still> requires the mental walk-through.

As experienced programmers, Herfried and myself can cope with compacted
statements. I usually write my code on the assumption that a (near) beginner
is going to take it over from me eventually. As that beginner programmer,
Meredith, you should write code that clear to <you>. Learning is your priority
at this stage.

Regards,
Fergus

ps. "feeble minded beginner programmer" is not 'allowed' when you're talking
to me, lol. You should be proud of having entered the arena, not apologetic.
Better to be assertive with a smile, eg "beginner programmer - gimme a break
;-)".
Besides 'feeble minded' and 'programmer' is a contradiction in terms. :-)

Nov 20 '05 #11

P: n/a
Hi Herfried, Meredith,

Better versus shorter:

If shorter means more efficient and efficency is <utmost> then shorter.

If shorter means you can see more on the page and you're me, then shorter.
Probably.

If shorter means cryptic - and clarity and understanding are important
(>95% of the time?) then longer.

If shorter means cryptic then comment and explain. (Which makes it longer
anyway!)

IMHO, lol.

Regards,
Fergus
Nov 20 '05 #12

P: n/a
Cor
Hi Herfried, Meredith,

Better versus shorter:

When shorter means not cryptic (skip this Meredith: by instance regex) than
shorter is in my opinion always better.

It is more readable, easier to keep up, better to trace, what not and seldom
it means more CPU power.
With some exceptions by instance graphical and sound questions, that are
very processor bound.

:-)
Cor
Nov 20 '05 #13

P: n/a
Cor
Fergus,
You like this is it not?
Gives you that real teacher feeling that you like?
:-)
Cor
Nov 20 '05 #14

P: n/a
Lol. Yep! :-D

Fergus
Nov 20 '05 #15

P: n/a
Hello,

"Fergus Cooney" <fi******@tesco.net> schrieb.
What's the objection - using comments or the comment I used? [...] ps. I know it's the latter but what don't you like about my
comment? And what would your preferred comment be?


IMO comments of this type are pretty useless:

\\\

' Increment i by 1.
i = i + 1
///

It's more important to describe _why_ we do that.

--
Herfried K. Wagner
MVP VB Classic, VB.NET
http://www.mvps.org/dotnet
Nov 20 '05 #16

P: n/a
Hi Herfried,

|| ' Increment i by 1.
|| i = i + 1

I totally agree that the above has nothing to offer as a comment (although
there are beginners who start out with this level of commenting).

However,
'Ignore the Key if it is not a digit.
e.Handled = Not Char.IsNumber(e.KeyChar)

conveys much more information. My post two steps above explains why I
believe so.

Regards,
Fergus


Nov 20 '05 #17

P: n/a
Hello,

"Fergus Cooney" <fi******@tesco.net> schrieb:
Better versus shorter:

If shorter means more efficient and efficency is <utmost>
then shorter.
In our case efficiency is not that important.
If shorter means you can see more on the page and you're
me, then shorter. Probably.
ACK.
If shorter means cryptic - and clarity and understanding
are important (>95% of the time?) then longer.
I think the line 'e.Handled = Not Char.IsNumber(e.KeyChar)' describes
exactly what and how I think. It doesn't reduce clarity and understanding
(IMO).
If shorter means cryptic then comment and explain.
(Which makes it longer anyway!)


Yep.

--
Herfried K. Wagner
MVP VB Classic, VB.NET
http://www.mvps.org/dotnet
Nov 20 '05 #18

P: n/a
Hello,

"Fergus Cooney" <fi******@tesco.net> schrieb:
|| ' Increment i by 1.
|| i = i + 1

I totally agree that the above has nothing to offer as
a comment (although there are beginners who start out
with this level of commenting).

However,
'Ignore the Key if it is not a digit.
e.Handled = Not Char.IsNumber(e.KeyChar)

conveys much more information. My post two steps
above explains why I believe so.


I don't agree. I place comments only to describe something that cannot be
seen when having a quick look at the source code. I do not include things
in my comments that help beginners to understand the code (syntax of the
programming language or the API). I assume the reader of the code to be
familiar with both. 'e.Handled = Not Char.IsNumber(e.KeyChar)' is IMO
really self-descriptive: "The character is handled if it is not a number".

--
Herfried K. Wagner
MVP VB Classic, VB.NET
http://www.mvps.org/dotnet
Nov 20 '05 #19

P: n/a
Hello,

"Cor" <no*@non.com> schrieb:
Better versus shorter:

When shorter means not cryptic (skip this Meredith: by
instance regex) than shorter is in my opinion always better.


'Regex' _can_ be shorter and less cryptic. This depends on the case. Why
not use advanced techniques only because beginners don't understand them?

--
Herfried K. Wagner
MVP VB Classic, VB.NET
http://www.mvps.org/dotnet
Nov 20 '05 #20

P: n/a
Cor
Hi Herfried,
That has nothing to do with beginners, the point for me in VB is, that it is
quiet easy to read as a natural document.

For me the first rule in architecture, documentation and programming is to
keep it simple

Someone else has to be able to read it in a quick look.

Therefore I try to avoid sophisticated commands that are not direct
meaningful or commands that needs comments

(Not ban them, if a process is in an often used loop, I try every command to
shorten that, I never did it but after that nice example from Fergus maybe
even the Regex)

On the other hand, I use always very complex program control structures.

By instance do I find functions like Mid, and Len more meaningful than
substring and length,

Of course you disagree that with me.

You are right because of the zero indexes and the generality I choose for
the String members.

:-)
Cor

Nov 20 '05 #21

P: n/a
Hello,

"Cor" <no*@non.com> schrieb:
That has nothing to do with beginners, the point for me in VB is,
that it is quiet easy to read as a natural document.
;-)

I think you really understood the meaning of "BASIC".
For me the first rule in architecture, documentation and
programming is to keep it simple

Someone else has to be able to read it in a quick look.

Therefore I try to avoid sophisticated commands that are
not direct meaningful or commands that needs comments
ACK.
shorten that, I never did it but after that nice example from
Fergus maybe even the Regex)
This depends on the case. For really complex string matching, extraction
and replacement routines it's sometimes "impossible" to write a solution
without using Regex because it would become much more complex and hard to
change and understand than the Regex solution.
By instance do I find functions like Mid, and Len more
meaningful than substring and length,
ACK.
Of course you disagree that with me.


I don't disagree.

--
Herfried K. Wagner
MVP VB Classic, VB.NET
http://www.mvps.org/dotnet
Nov 20 '05 #22

P: n/a
Cor
Hi,
By instance do I find functions like Mid, and Len more
meaningful than substring and length,

I know you don't disagree that, but I use the String members, that is
inconsequent with my text, so I had to tell why.
:-))
Cor
Nov 20 '05 #23

P: n/a
Hello,

"Fergus Cooney" <fi******@tesco.net> schrieb:
Handled = False is techie for 'keep the key'
Handled = False is techie for 'throw the key away'.


Typo:

Handled = False is techie for 'keep the key'
Handled = True is techie for 'throw the key away'.

That's why I prefer the short version.

;-)

--
Herfried K. Wagner
MVP VB Classic, VB.NET
http://www.mvps.org/dotnet
Nov 20 '05 #24

P: n/a
The code worked in one way, and not another :(

Now I cannot type a "." for decimals! Its great to know
how to enter a number only, how do I tell the program to
only allow digits and a few other keys, like the period,
the regular enter, backspace ... etc.

Also, I tried to add the code to have the calculator
validate that an entry was in txtBox 1 and 2 before
Enabling the Operation buttons, but I couldn't figure it
out. SHould I already know how to Validate, because I
don't :).

Thanks for all the info!

-----Original Message-----
Hi Meredith, Herfried,

Nice to know your name, Meredith :-)

Sorry if that was confusing. Shorter is better when you are comfortablewith it. Comments should be used when there is any doubt or when the code doessomething techie which doesn't explain what it's doing in conceptual terms.
Handled = False is techie for 'keep the key'
Handled = False is techie for 'throw the key away'.

e.Handled = Not Char.IsNumber(e.KeyChar) is techie for "keep the key onlyif it is a digit".

I disaprove of such code when it obscures the meaning. To understand ityou have to do some mental hoop-la before you know which way it jumps. - Ok,I've got a key and it <is> a number, so <Not that> means it's False, soHandled = False, now that means I <haven't> dealt with the key so that I <do>want to keep it. Okay. Glad <that's> clear. Now if it <isn't> a number keythen......

At least with a comment you can know what the code is doing, even ifchecking it <still> requires the mental walk-through.

As experienced programmers, Herfried and myself can cope with compactedstatements. I usually write my code on the assumption that a (near) beginneris going to take it over from me eventually. As that beginner programmer,Meredith, you should write code that clear to <you>. Learning is your priorityat this stage.

Regards,
Fergus

ps. "feeble minded beginner programmer" is not 'allowed' when you're talkingto me, lol. You should be proud of having entered the arena, not apologetic.Better to be assertive with a smile, eg "beginner programmer - gimme a break;-)".
Besides 'feeble minded' and 'programmer' is a contradiction in terms. :-)
.

Nov 20 '05 #25

P: n/a
Hello,

"meredith" <mh********@hotmail.com> schrieb:
Now I cannot type a "." for decimals! Its great to know
how to enter a number only, how do I tell the program to
only allow digits and a few other keys, like the period,
the regular enter, backspace ... etc.

Also, I tried to add the code to have the calculator
validate that an entry was in txtBox 1 and 2 before
Enabling the Operation buttons, but I couldn't figure it
out. SHould I already know how to Validate, because I
don't :).


Why not use a NumericUpDown control or validate the textbox's contents in
its 'Validating' event? Restricting the user to some keys is always a bad
idea. When uding 'KeyDown' to suppress some keys, the user will still be
able to paste text into the texbox.

--
Herfried K. Wagner
MVP VB Classic, VB.NET
http://www.mvps.org/dotnet
Nov 20 '05 #26

P: n/a
Hi Herfried, Meredith,

|| Why not use a NumericUpDown control.

Lol, It won't take long to get to 3675 and not much longer to reach
438173. :-)

|| or validate the textbox's contents in its 'Validating' event?

Because Meredith wants dynamic reaction. The [+], [-],[*], [/] buttons
enabled as and when and only when the inputs are valid, ie per character.

|| Restricting the user to some keys is always a bad idea.

Is it? Always? Lol.

I think you should prevent the user doing what they shouldn't then you
don't have to tell them off when they get it wrong. ["No, you can't type a
letter into the calculation", or even better "Data Error", or better still
"Error 54"]

|| When using 'KeyDown' to suppress some keys, the user will
|| still be able to paste text into the texbox.

Now you're making sense. I faced exactly the same problem when I did this
exercise.

=================================
Meredith,

One option on validation is that you let the user do what they want but if
a box has a bad value, set its background to some suitable colour, eg light
red. and put the nature of the error in the status bar. This informs the user
of the error without interrupting them with dialogue boxes. It also allows
them to intentionally use cut-and-paste to bring in mixed data, eg "23 Files",
and edit out the rubbish - again without pesky interruptions from a dialogue
box.

In this case you would act upon the TextBox_Change events. If the text is
not empty and contains only digits then set it's background to the 'good'
colour and clear the status panel for that box. Otherwise set it to the 'bad'
colour and put a message in the status bar panel for that box. Then do the
same for the other text. Then, if both are ok, enable the calculation buttons.
Otherwise disable them.

By the way, allow leading and trailing spaces in the input. It's annoying
to a user to have to delete spaces which <they> know don't matter. Especially
if the font makes them narrow and they haven't wiped their glasses. But, of
course, take them off before using the number.

This makes for a very unintrusive UI - informative, obvious and with no
interruptions to the user's work flow. There's no harm in keeping the
disablement of alpha/punctuation keys.

Hope this gives you some ideas. :-)

Regards,
Fergus
Nov 20 '05 #27

P: n/a
Hi Meredith,

See my response to Herfried for some ideas. I'll assume that you've read
that one first.

Whatever you did to allow the digit keys to go through, you have to do the
same for the special keys that you are interested in. Use the Keys
enumeraction to get the key values for the full stop (Keys.Decimal?), etc.

Write a function that takes a string and returns true if it's valid and
creates a meaningful error message if it's not.

Validition:
On copy of the string (ie ByVal parameter)
Strip the leading and traiing spaces
Allow a single "-" at the front. Remove it. Strip leading spaces.
Check for any more "-"s. Error - "Only one minus is allowed and it
must be at the front."
Check for "." and, if found, remove it.
Check for ".", and if found. Error - "There may only be a single
decimal point"
Check for non digits. Error - "Numbers may only contain a minus,
digits and a decimal point"

Like I say in the other post. Validate both texts separately and put their
error messages in their respective status bar panels. Use the combination of
both validities for button enabling.

That should keep you busy for a while. :-)

Let us know how you are getting on. You may want to post your code.

See you later,
Fergus
Nov 20 '05 #28

This discussion thread is closed

Replies have been disabled for this discussion.