|
Answer» I'm doing a project for my CS116 where the program has to generate an error message in a label when a user inputs a non numeric character in a text box and then presses a button. I've spent hours googling this on top of using my textbook and I just can't figure it out. I would do SOMETHING like
try { quantityinteger = int.Parse(quantityTextBox.Text); QuantityTextBox.Text = quantityInteger.ToString(); } catch { label1.Text = "Error"; }
but I get a 'FormatException was unhandled' error. I don't really know what I'm doing, I'm just copying this out of my book.. I've tried to understand try catch for quite a while and it still is really confusing to me.
Teacher recommends try catch, but doesn't care as long as it will work. And I can't make the textbox only be able to input numbers, it has to be SET up to fail.
Thanks in ADVANCE.. If you can't tell I'm very very new at C# and programming in general, so I might need some more explanation than the average computer programming forum user
This may help: http://msdn.microsoft.com/en-us/library/b3h1hf19.aspxcorrect code like this
try { int quantityinteger; quantityinteger = int.Parse(quantityTextBox.Text); quantityTextBox.Text = quantityinteger.ToString(); } catch { label1.Text = "Error"; }
'FormatException was unhandled' - should learn about exceptions first
http://csharp.net-informations.com/statements/csharp-exceptions.htm
Basics of exceptions explain in the above link
Merca Try and catch blocks are not that hard to be understood, when code which is written inside a try block ( try block means the code written between {} parenthesis) raises an error (something like giving a text value for a numeric one lets say you want "ana" kilograms of apples) an error is raising and your program will automatically run form code which is inside the catch block ( in your case giving an error on user interface (Number of kilograms must be a numeric value ! for instance ). Woah. Talk about thread necromancy. Actually, in this case using an Exception to deal with it is silly. the .Parse() functions were an API design blunder because they shouldn't be throwing exceptions in the first place.
Code: [SELECT]int quantityinteger=0; QuantityTextBox.Text = int.TryParse(quantityTextBox.Text,out quantityinteger)?quantityinteger.ToString():"Error";
with the type.Parse() methods, you pay the Exception TAX. Usually when you use the method you just end up catching the error and setting a default, returning false, etc. so unless this Parse failure will cause code to throw it's own exception- such as an argument exception- TryParse() is the better choice.BC_Programmer is right.
|