C# backspace on textbox creating errors immediately











up vote
-1
down vote

favorite












I am creating an event where if someone types into a text box it will show an error using this code:



try
{
dblCostSqFt = double.Parse(txtCost.Text);
}
catch
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtCost.Select();
return;
}


The issue with this is if I input a backspace it will throw that error message immediately I would like to make it to where that doesn't happen.










share|improve this question




















  • 1




    I imagine you probably have a method assigned for validating text that is linked to your textbox textchanged event, so any time the text changes at all (including backspace) it checks for valid input, and if it isn't valid it throws the error.
    – emsimpson92
    Nov 9 at 21:34






  • 4




    Critical info missing. Which event handler contains the code posted?
    – Steve
    Nov 9 at 21:37






  • 1




    Use TryParse instead.
    – LarsTech
    Nov 9 at 21:37






  • 1




    Maybe first check whether there is text in that textbox and ignore (without message) if it is empty
    – Hans Kesting
    Nov 9 at 21:43






  • 5




    I'll let the other contributors address your validation logic. I'll just chime in to say: please do not display a modal dialog while a user is editing a field. That's one of the most user-hostile things you can do as a UX developer. Better to display an inline error indicator, or at minimum wait until they've finished typing (e.g., focus has left the text box, or some sort of 'commit' action is taken).
    – Mike Strobel
    Nov 9 at 22:02

















up vote
-1
down vote

favorite












I am creating an event where if someone types into a text box it will show an error using this code:



try
{
dblCostSqFt = double.Parse(txtCost.Text);
}
catch
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtCost.Select();
return;
}


The issue with this is if I input a backspace it will throw that error message immediately I would like to make it to where that doesn't happen.










share|improve this question




















  • 1




    I imagine you probably have a method assigned for validating text that is linked to your textbox textchanged event, so any time the text changes at all (including backspace) it checks for valid input, and if it isn't valid it throws the error.
    – emsimpson92
    Nov 9 at 21:34






  • 4




    Critical info missing. Which event handler contains the code posted?
    – Steve
    Nov 9 at 21:37






  • 1




    Use TryParse instead.
    – LarsTech
    Nov 9 at 21:37






  • 1




    Maybe first check whether there is text in that textbox and ignore (without message) if it is empty
    – Hans Kesting
    Nov 9 at 21:43






  • 5




    I'll let the other contributors address your validation logic. I'll just chime in to say: please do not display a modal dialog while a user is editing a field. That's one of the most user-hostile things you can do as a UX developer. Better to display an inline error indicator, or at minimum wait until they've finished typing (e.g., focus has left the text box, or some sort of 'commit' action is taken).
    – Mike Strobel
    Nov 9 at 22:02















up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











I am creating an event where if someone types into a text box it will show an error using this code:



try
{
dblCostSqFt = double.Parse(txtCost.Text);
}
catch
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtCost.Select();
return;
}


The issue with this is if I input a backspace it will throw that error message immediately I would like to make it to where that doesn't happen.










share|improve this question















I am creating an event where if someone types into a text box it will show an error using this code:



try
{
dblCostSqFt = double.Parse(txtCost.Text);
}
catch
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtCost.Select();
return;
}


The issue with this is if I input a backspace it will throw that error message immediately I would like to make it to where that doesn't happen.







c#






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 9 at 22:03









Rufus L

16.4k31529




16.4k31529










asked Nov 9 at 21:32









Joseph Markley

1




1








  • 1




    I imagine you probably have a method assigned for validating text that is linked to your textbox textchanged event, so any time the text changes at all (including backspace) it checks for valid input, and if it isn't valid it throws the error.
    – emsimpson92
    Nov 9 at 21:34






  • 4




    Critical info missing. Which event handler contains the code posted?
    – Steve
    Nov 9 at 21:37






  • 1




    Use TryParse instead.
    – LarsTech
    Nov 9 at 21:37






  • 1




    Maybe first check whether there is text in that textbox and ignore (without message) if it is empty
    – Hans Kesting
    Nov 9 at 21:43






  • 5




    I'll let the other contributors address your validation logic. I'll just chime in to say: please do not display a modal dialog while a user is editing a field. That's one of the most user-hostile things you can do as a UX developer. Better to display an inline error indicator, or at minimum wait until they've finished typing (e.g., focus has left the text box, or some sort of 'commit' action is taken).
    – Mike Strobel
    Nov 9 at 22:02
















  • 1




    I imagine you probably have a method assigned for validating text that is linked to your textbox textchanged event, so any time the text changes at all (including backspace) it checks for valid input, and if it isn't valid it throws the error.
    – emsimpson92
    Nov 9 at 21:34






  • 4




    Critical info missing. Which event handler contains the code posted?
    – Steve
    Nov 9 at 21:37






  • 1




    Use TryParse instead.
    – LarsTech
    Nov 9 at 21:37






  • 1




    Maybe first check whether there is text in that textbox and ignore (without message) if it is empty
    – Hans Kesting
    Nov 9 at 21:43






  • 5




    I'll let the other contributors address your validation logic. I'll just chime in to say: please do not display a modal dialog while a user is editing a field. That's one of the most user-hostile things you can do as a UX developer. Better to display an inline error indicator, or at minimum wait until they've finished typing (e.g., focus has left the text box, or some sort of 'commit' action is taken).
    – Mike Strobel
    Nov 9 at 22:02










1




1




I imagine you probably have a method assigned for validating text that is linked to your textbox textchanged event, so any time the text changes at all (including backspace) it checks for valid input, and if it isn't valid it throws the error.
– emsimpson92
Nov 9 at 21:34




I imagine you probably have a method assigned for validating text that is linked to your textbox textchanged event, so any time the text changes at all (including backspace) it checks for valid input, and if it isn't valid it throws the error.
– emsimpson92
Nov 9 at 21:34




4




4




Critical info missing. Which event handler contains the code posted?
– Steve
Nov 9 at 21:37




Critical info missing. Which event handler contains the code posted?
– Steve
Nov 9 at 21:37




1




1




Use TryParse instead.
– LarsTech
Nov 9 at 21:37




Use TryParse instead.
– LarsTech
Nov 9 at 21:37




1




1




Maybe first check whether there is text in that textbox and ignore (without message) if it is empty
– Hans Kesting
Nov 9 at 21:43




Maybe first check whether there is text in that textbox and ignore (without message) if it is empty
– Hans Kesting
Nov 9 at 21:43




5




5




I'll let the other contributors address your validation logic. I'll just chime in to say: please do not display a modal dialog while a user is editing a field. That's one of the most user-hostile things you can do as a UX developer. Better to display an inline error indicator, or at minimum wait until they've finished typing (e.g., focus has left the text box, or some sort of 'commit' action is taken).
– Mike Strobel
Nov 9 at 22:02






I'll let the other contributors address your validation logic. I'll just chime in to say: please do not display a modal dialog while a user is editing a field. That's one of the most user-hostile things you can do as a UX developer. Better to display an inline error indicator, or at minimum wait until they've finished typing (e.g., focus has left the text box, or some sort of 'commit' action is taken).
– Mike Strobel
Nov 9 at 22:02














2 Answers
2






active

oldest

votes

















up vote
0
down vote













You're working with userinput here. Therefore i'd suggest to use Double.TryParse()





  • If you've got a string, and you expect it to always be a double (say, if some web service is handing you a double in string format), you'd use Double.Parse().


  • If you're collecting input from a user, you'd generally use Double.TryParse(), since it allows you more fine-grained control over the situation when the user enters invalid input.





With tryparse() your code will be something like this:



if (!double.TryParse(txtCost.Text, out var dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtCost.Text.Length);
return;
}


To make the example complete and address the issue one could simply check if the Text is not null or empty by using String.IsNullOrEmpty() making the whole code:



// makes sure your app isn't crashing upon backspaces.
if(string.IsNullOrEmpty(textCost.Text))
{
// Personally i'd indicate the user nothing is typed in (yet).
return;
}
if (!double.TryParse(txtCost.Text, out var dblCostSqFt))
{
// The user filled in something that can't be parse to doubles.
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtCost.Text.Length);
return;
}
// All is great; Do stuff with dblCostSqFt.





share|improve this answer



















  • 1




    You don't need to initialize dblCostSqFt, you set it in the next line. And, if you are using a recent version of the C# compiler, you could have simply said: if (!double.TryParse(txtCost.Text, out var dblCostSqFt)), declaring the variable inline.
    – Flydog57
    Nov 9 at 21:58






  • 1




    While this is good advice, it doesn't address the question of how to avoid showing the error when the backspace key is pressed.
    – Rufus L
    Nov 9 at 22:05










  • Neither did OP show us how he currently has implemented key listeners. With a dependency of that there's only a posibility to check if the text is null or empty and if it is return. Making the app not crash
    – Baklap4
    Nov 9 at 22:21


















up vote
0
down vote













Assuming you are using WPF for your UI without straying too far from what you have I would use something like below (as LarsTech suggested, use TryParse to test if the value can be converted). Note the if block surrounding the core code within the function, you can avoid execution entering the if block by checking if the key pressed was backspace. I also added a check for the enter key as many users would press the enter key to close the MessageBox, which would cause the event to trigger once again.



private void txtExample_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key != Key.Back && e.Key != Key.Enter)
{
double dblCostSqFt = 0;

if (!double.TryParse(txtExample.Text, out dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtExample.Text.Length);
}
}
}


Never rely on exception handling to control the workflow of your application, exceptions have a ton of overhead and it is typically a bad practice in general.



You can accomplish the same thing in WinForms as well using the following...



private void txtExample_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Back && e.KeyCode != Keys.Enter)
{
double dblCostSqFt = 0;

if (!double.TryParse(txtExample.Text, out dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select();
}
}
}


It looks like you are using WinForms because your textbox.Select function call does not supply any arguments, only WinForms supports an overload of the select function without any arguments.






share|improve this answer























  • Agreeing with @NickHanshaw... The mnemonic is "only use exceptions for exceptional conditions". Users entering bad data is the opposite of exceptional - it's to be expected.
    – Flydog57
    Nov 9 at 21:54












  • Flydog57 well said sir
    – Nick Hanshaw
    Nov 9 at 21:59











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53233521%2fc-sharp-backspace-on-textbox-creating-errors-immediately%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
0
down vote













You're working with userinput here. Therefore i'd suggest to use Double.TryParse()





  • If you've got a string, and you expect it to always be a double (say, if some web service is handing you a double in string format), you'd use Double.Parse().


  • If you're collecting input from a user, you'd generally use Double.TryParse(), since it allows you more fine-grained control over the situation when the user enters invalid input.





With tryparse() your code will be something like this:



if (!double.TryParse(txtCost.Text, out var dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtCost.Text.Length);
return;
}


To make the example complete and address the issue one could simply check if the Text is not null or empty by using String.IsNullOrEmpty() making the whole code:



// makes sure your app isn't crashing upon backspaces.
if(string.IsNullOrEmpty(textCost.Text))
{
// Personally i'd indicate the user nothing is typed in (yet).
return;
}
if (!double.TryParse(txtCost.Text, out var dblCostSqFt))
{
// The user filled in something that can't be parse to doubles.
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtCost.Text.Length);
return;
}
// All is great; Do stuff with dblCostSqFt.





share|improve this answer



















  • 1




    You don't need to initialize dblCostSqFt, you set it in the next line. And, if you are using a recent version of the C# compiler, you could have simply said: if (!double.TryParse(txtCost.Text, out var dblCostSqFt)), declaring the variable inline.
    – Flydog57
    Nov 9 at 21:58






  • 1




    While this is good advice, it doesn't address the question of how to avoid showing the error when the backspace key is pressed.
    – Rufus L
    Nov 9 at 22:05










  • Neither did OP show us how he currently has implemented key listeners. With a dependency of that there's only a posibility to check if the text is null or empty and if it is return. Making the app not crash
    – Baklap4
    Nov 9 at 22:21















up vote
0
down vote













You're working with userinput here. Therefore i'd suggest to use Double.TryParse()





  • If you've got a string, and you expect it to always be a double (say, if some web service is handing you a double in string format), you'd use Double.Parse().


  • If you're collecting input from a user, you'd generally use Double.TryParse(), since it allows you more fine-grained control over the situation when the user enters invalid input.





With tryparse() your code will be something like this:



if (!double.TryParse(txtCost.Text, out var dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtCost.Text.Length);
return;
}


To make the example complete and address the issue one could simply check if the Text is not null or empty by using String.IsNullOrEmpty() making the whole code:



// makes sure your app isn't crashing upon backspaces.
if(string.IsNullOrEmpty(textCost.Text))
{
// Personally i'd indicate the user nothing is typed in (yet).
return;
}
if (!double.TryParse(txtCost.Text, out var dblCostSqFt))
{
// The user filled in something that can't be parse to doubles.
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtCost.Text.Length);
return;
}
// All is great; Do stuff with dblCostSqFt.





share|improve this answer



















  • 1




    You don't need to initialize dblCostSqFt, you set it in the next line. And, if you are using a recent version of the C# compiler, you could have simply said: if (!double.TryParse(txtCost.Text, out var dblCostSqFt)), declaring the variable inline.
    – Flydog57
    Nov 9 at 21:58






  • 1




    While this is good advice, it doesn't address the question of how to avoid showing the error when the backspace key is pressed.
    – Rufus L
    Nov 9 at 22:05










  • Neither did OP show us how he currently has implemented key listeners. With a dependency of that there's only a posibility to check if the text is null or empty and if it is return. Making the app not crash
    – Baklap4
    Nov 9 at 22:21













up vote
0
down vote










up vote
0
down vote









You're working with userinput here. Therefore i'd suggest to use Double.TryParse()





  • If you've got a string, and you expect it to always be a double (say, if some web service is handing you a double in string format), you'd use Double.Parse().


  • If you're collecting input from a user, you'd generally use Double.TryParse(), since it allows you more fine-grained control over the situation when the user enters invalid input.





With tryparse() your code will be something like this:



if (!double.TryParse(txtCost.Text, out var dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtCost.Text.Length);
return;
}


To make the example complete and address the issue one could simply check if the Text is not null or empty by using String.IsNullOrEmpty() making the whole code:



// makes sure your app isn't crashing upon backspaces.
if(string.IsNullOrEmpty(textCost.Text))
{
// Personally i'd indicate the user nothing is typed in (yet).
return;
}
if (!double.TryParse(txtCost.Text, out var dblCostSqFt))
{
// The user filled in something that can't be parse to doubles.
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtCost.Text.Length);
return;
}
// All is great; Do stuff with dblCostSqFt.





share|improve this answer














You're working with userinput here. Therefore i'd suggest to use Double.TryParse()





  • If you've got a string, and you expect it to always be a double (say, if some web service is handing you a double in string format), you'd use Double.Parse().


  • If you're collecting input from a user, you'd generally use Double.TryParse(), since it allows you more fine-grained control over the situation when the user enters invalid input.





With tryparse() your code will be something like this:



if (!double.TryParse(txtCost.Text, out var dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtCost.Text.Length);
return;
}


To make the example complete and address the issue one could simply check if the Text is not null or empty by using String.IsNullOrEmpty() making the whole code:



// makes sure your app isn't crashing upon backspaces.
if(string.IsNullOrEmpty(textCost.Text))
{
// Personally i'd indicate the user nothing is typed in (yet).
return;
}
if (!double.TryParse(txtCost.Text, out var dblCostSqFt))
{
// The user filled in something that can't be parse to doubles.
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtCost.Text.Length);
return;
}
// All is great; Do stuff with dblCostSqFt.






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 9 at 22:23

























answered Nov 9 at 21:56









Baklap4

1,33811235




1,33811235








  • 1




    You don't need to initialize dblCostSqFt, you set it in the next line. And, if you are using a recent version of the C# compiler, you could have simply said: if (!double.TryParse(txtCost.Text, out var dblCostSqFt)), declaring the variable inline.
    – Flydog57
    Nov 9 at 21:58






  • 1




    While this is good advice, it doesn't address the question of how to avoid showing the error when the backspace key is pressed.
    – Rufus L
    Nov 9 at 22:05










  • Neither did OP show us how he currently has implemented key listeners. With a dependency of that there's only a posibility to check if the text is null or empty and if it is return. Making the app not crash
    – Baklap4
    Nov 9 at 22:21














  • 1




    You don't need to initialize dblCostSqFt, you set it in the next line. And, if you are using a recent version of the C# compiler, you could have simply said: if (!double.TryParse(txtCost.Text, out var dblCostSqFt)), declaring the variable inline.
    – Flydog57
    Nov 9 at 21:58






  • 1




    While this is good advice, it doesn't address the question of how to avoid showing the error when the backspace key is pressed.
    – Rufus L
    Nov 9 at 22:05










  • Neither did OP show us how he currently has implemented key listeners. With a dependency of that there's only a posibility to check if the text is null or empty and if it is return. Making the app not crash
    – Baklap4
    Nov 9 at 22:21








1




1




You don't need to initialize dblCostSqFt, you set it in the next line. And, if you are using a recent version of the C# compiler, you could have simply said: if (!double.TryParse(txtCost.Text, out var dblCostSqFt)), declaring the variable inline.
– Flydog57
Nov 9 at 21:58




You don't need to initialize dblCostSqFt, you set it in the next line. And, if you are using a recent version of the C# compiler, you could have simply said: if (!double.TryParse(txtCost.Text, out var dblCostSqFt)), declaring the variable inline.
– Flydog57
Nov 9 at 21:58




1




1




While this is good advice, it doesn't address the question of how to avoid showing the error when the backspace key is pressed.
– Rufus L
Nov 9 at 22:05




While this is good advice, it doesn't address the question of how to avoid showing the error when the backspace key is pressed.
– Rufus L
Nov 9 at 22:05












Neither did OP show us how he currently has implemented key listeners. With a dependency of that there's only a posibility to check if the text is null or empty and if it is return. Making the app not crash
– Baklap4
Nov 9 at 22:21




Neither did OP show us how he currently has implemented key listeners. With a dependency of that there's only a posibility to check if the text is null or empty and if it is return. Making the app not crash
– Baklap4
Nov 9 at 22:21












up vote
0
down vote













Assuming you are using WPF for your UI without straying too far from what you have I would use something like below (as LarsTech suggested, use TryParse to test if the value can be converted). Note the if block surrounding the core code within the function, you can avoid execution entering the if block by checking if the key pressed was backspace. I also added a check for the enter key as many users would press the enter key to close the MessageBox, which would cause the event to trigger once again.



private void txtExample_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key != Key.Back && e.Key != Key.Enter)
{
double dblCostSqFt = 0;

if (!double.TryParse(txtExample.Text, out dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtExample.Text.Length);
}
}
}


Never rely on exception handling to control the workflow of your application, exceptions have a ton of overhead and it is typically a bad practice in general.



You can accomplish the same thing in WinForms as well using the following...



private void txtExample_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Back && e.KeyCode != Keys.Enter)
{
double dblCostSqFt = 0;

if (!double.TryParse(txtExample.Text, out dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select();
}
}
}


It looks like you are using WinForms because your textbox.Select function call does not supply any arguments, only WinForms supports an overload of the select function without any arguments.






share|improve this answer























  • Agreeing with @NickHanshaw... The mnemonic is "only use exceptions for exceptional conditions". Users entering bad data is the opposite of exceptional - it's to be expected.
    – Flydog57
    Nov 9 at 21:54












  • Flydog57 well said sir
    – Nick Hanshaw
    Nov 9 at 21:59















up vote
0
down vote













Assuming you are using WPF for your UI without straying too far from what you have I would use something like below (as LarsTech suggested, use TryParse to test if the value can be converted). Note the if block surrounding the core code within the function, you can avoid execution entering the if block by checking if the key pressed was backspace. I also added a check for the enter key as many users would press the enter key to close the MessageBox, which would cause the event to trigger once again.



private void txtExample_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key != Key.Back && e.Key != Key.Enter)
{
double dblCostSqFt = 0;

if (!double.TryParse(txtExample.Text, out dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtExample.Text.Length);
}
}
}


Never rely on exception handling to control the workflow of your application, exceptions have a ton of overhead and it is typically a bad practice in general.



You can accomplish the same thing in WinForms as well using the following...



private void txtExample_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Back && e.KeyCode != Keys.Enter)
{
double dblCostSqFt = 0;

if (!double.TryParse(txtExample.Text, out dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select();
}
}
}


It looks like you are using WinForms because your textbox.Select function call does not supply any arguments, only WinForms supports an overload of the select function without any arguments.






share|improve this answer























  • Agreeing with @NickHanshaw... The mnemonic is "only use exceptions for exceptional conditions". Users entering bad data is the opposite of exceptional - it's to be expected.
    – Flydog57
    Nov 9 at 21:54












  • Flydog57 well said sir
    – Nick Hanshaw
    Nov 9 at 21:59













up vote
0
down vote










up vote
0
down vote









Assuming you are using WPF for your UI without straying too far from what you have I would use something like below (as LarsTech suggested, use TryParse to test if the value can be converted). Note the if block surrounding the core code within the function, you can avoid execution entering the if block by checking if the key pressed was backspace. I also added a check for the enter key as many users would press the enter key to close the MessageBox, which would cause the event to trigger once again.



private void txtExample_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key != Key.Back && e.Key != Key.Enter)
{
double dblCostSqFt = 0;

if (!double.TryParse(txtExample.Text, out dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtExample.Text.Length);
}
}
}


Never rely on exception handling to control the workflow of your application, exceptions have a ton of overhead and it is typically a bad practice in general.



You can accomplish the same thing in WinForms as well using the following...



private void txtExample_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Back && e.KeyCode != Keys.Enter)
{
double dblCostSqFt = 0;

if (!double.TryParse(txtExample.Text, out dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select();
}
}
}


It looks like you are using WinForms because your textbox.Select function call does not supply any arguments, only WinForms supports an overload of the select function without any arguments.






share|improve this answer














Assuming you are using WPF for your UI without straying too far from what you have I would use something like below (as LarsTech suggested, use TryParse to test if the value can be converted). Note the if block surrounding the core code within the function, you can avoid execution entering the if block by checking if the key pressed was backspace. I also added a check for the enter key as many users would press the enter key to close the MessageBox, which would cause the event to trigger once again.



private void txtExample_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key != Key.Back && e.Key != Key.Enter)
{
double dblCostSqFt = 0;

if (!double.TryParse(txtExample.Text, out dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtExample.Text.Length);
}
}
}


Never rely on exception handling to control the workflow of your application, exceptions have a ton of overhead and it is typically a bad practice in general.



You can accomplish the same thing in WinForms as well using the following...



private void txtExample_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Back && e.KeyCode != Keys.Enter)
{
double dblCostSqFt = 0;

if (!double.TryParse(txtExample.Text, out dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select();
}
}
}


It looks like you are using WinForms because your textbox.Select function call does not supply any arguments, only WinForms supports an overload of the select function without any arguments.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 9 at 22:46

























answered Nov 9 at 21:51









Nick Hanshaw

1014




1014












  • Agreeing with @NickHanshaw... The mnemonic is "only use exceptions for exceptional conditions". Users entering bad data is the opposite of exceptional - it's to be expected.
    – Flydog57
    Nov 9 at 21:54












  • Flydog57 well said sir
    – Nick Hanshaw
    Nov 9 at 21:59


















  • Agreeing with @NickHanshaw... The mnemonic is "only use exceptions for exceptional conditions". Users entering bad data is the opposite of exceptional - it's to be expected.
    – Flydog57
    Nov 9 at 21:54












  • Flydog57 well said sir
    – Nick Hanshaw
    Nov 9 at 21:59
















Agreeing with @NickHanshaw... The mnemonic is "only use exceptions for exceptional conditions". Users entering bad data is the opposite of exceptional - it's to be expected.
– Flydog57
Nov 9 at 21:54






Agreeing with @NickHanshaw... The mnemonic is "only use exceptions for exceptional conditions". Users entering bad data is the opposite of exceptional - it's to be expected.
– Flydog57
Nov 9 at 21:54














Flydog57 well said sir
– Nick Hanshaw
Nov 9 at 21:59




Flydog57 well said sir
– Nick Hanshaw
Nov 9 at 21:59


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53233521%2fc-sharp-backspace-on-textbox-creating-errors-immediately%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Schultheiß

Verwaltungsgliederung Dänemarks

Liste der Kulturdenkmale in Wilsdruff