Question Input String error when Winform Textboxes are blank

agnl225

Member
Joined
Jun 12, 2019
Messages
11
Programming Experience
Beginner
Hi,
I'm brand new to C# and more proficient in VBA but I was designing something basic for work purposes and I'm stuck. The form works well when data is entered, however I'm getting an error when my windows form app is blank and i think the cause is the conversion of the timespan difference to decimal? I used tryparse,parse,convert and it is still not working properly when the form is blank and the button is clicked. Any suggestions would be greatly appreciated! Error message below and code below that.

Thanks!

544




C#:
private void Button1_Click(object sender, EventArgs e)
        {
            if
                   (textBox4.Text == "")
            {
                MessageBox.Show("Please Enter Payment Agreement Amount");
            }

            if
                    (comboBox2.Items.Count == 0)
            {
                MessageBox.Show("Please Select A Payment Type");
            }
            else
            {
                DateTime date1 = dateTimePicker3.Value;
                DateTime date2 = dateTimePicker2.Value;
                TimeSpan difference = date1 - date2;
                decimal TotalWeeks = difference.Days / 7;
                decimal PayTotal = decimal.Parse(textBox4.Text);
                decimal PaymentWeeks = TotalWeeks * PayTotal;
                decimal TotalMonths = difference.Days / 30;
                decimal PaymentMonths = TotalMonths * PayTotal;
                if (comboBox2.SelectedItem == "Months")
                    textBox3.Text = String.Format("$" + "{0:0,0.00}", Convert.ToDecimal(PaymentMonths));
                if (comboBox2.SelectedItem == "Weeks")
                    textBox3.Text = String.Format("$" + "{0:0,0.00}", Convert.ToDecimal(PaymentWeeks));
            }
 

Attachments

  • 1560356956059.png
    1560356956059.png
    21.4 KB · Views: 77
Last edited by a moderator:
Why are you converting to decimal when PaymentMonths and PaymentWeeks are already declared as decimal. See:
C#:
decimal PaymentWeeks = TotalWeeks * PayTotal;
:
decimal PaymentMonths = TotalMonths * PayTotal;
 
I thought I had to give them a designation when I multiply it would it just be Payweeks =
Totalweeks * Paytotal ? Is that the issue?
 
The callstack seems to point to Convert.ToDecimal(), but the code you presented above says this:
C#:
decimal PayTotal = decimal.Parse(textBox4.Text);

That should also throw an exception if textBox4.Text is empty, but the callstack presented to you should look different. It should have decimal.Parse() in the callstack instead of Convert.ToDecimal(). Anyway, the better way to deal with it is check for an empty string like you were doing in your code earlier AND then exit out of the method. Your current code brings up the message box, and then continues on.
An even better way is to use TryParse(). That shouldn't throw an exception.
And yet an even better way is to take advantage of the WinForm Validating and Validated events to ensure that your form is in a good state even before you get to the button click event.
 
I thought I had to give them a designation when I multiply it would it just be Payweeks =
Totalweeks * Paytotal ? Is that the issue?
Yes you need to declare the type. But once the type is decimal there is no need to convert to a decimal again with:
C#:
textBox3.Text = String.Format("$" + "{0:0,0.00}", Convert.ToDecimal(PaymentMonths));
:
textBox3.Text = String.Format("$" + "{0:0,0.00}", Convert.ToDecimal(PaymentWeeks));
 
Well now I’m getting an unhandled exception and the form won’t even run properly :( atleast I published a working version I’m just gonna have to rebuild
 
Instead of pressing Ctrl-F5, just Press F5. That way when you get an unhandled exception, Visual Studio will take you right to the offending line and you can even inspect the values of variables.

Please report back which line of code is throwing the exception and what the values of the pertinent variables are.
 
when the form is blank and the button is clicked
decimal PayTotal = decimal.Parse(textBox4.Text);
Decimal.Parse Method (System) | Microsoft Docs
Exceptions
ArgumentNullException
s is null.
FormatException
s is not in the correct format.
When textbox is empty Text property doesn't return null, it returns en empty string, and that is not a valid format for a decimal value. You can check if the requied input is valid before starting calculations. That is also what you have attempted with first if statement, but then you just show a messagebox, ignore the test and continue with calculations anyway. Rework your if statement to avoid doing decimal.Parse when Text is empty string.

Since user may input anything in the textbox, which also may not be a decimal, the advice to use TryParse is good, also for this you need if statement to check when the parsing is successful.
 
For fields that you know will be in a particular range but you still want people to be able to type in values if they wish, I often recommend using the NumericUpDown control. If you don't want them to type in a value, they can use a TrackBar control. I personally don't like dropdown comboboxes when there are more than 10-15 choices.

Also, as a warning, as tempting as it is to use MaskedTextBox control, you are doing your users a major disservice. The UI for the old dBase and Foxbase masked input fields were amazing. The MaskedTextBox will cause your users to show up at your home with torches and pitchforks.
 
Last edited:
The input in textbox is not a date, it is the amount of payment. Still, a NumericUpDown control would be more suitable than a TextBox.
 
Right, I’m using 2 date time pickers but I’m getting the difference of the 2 dates and then dividing the days by 7 and 30 to get the weeks and months difference so I can multiply that times the paytotal value and I want the textbox to reflect a different figure depending on which combobox option(months and years) they select and if the textbox denoting payment is blank or the combobox is not selected I want a messageBox to pop up saying “Please Select Payment Type” or “Please Enter Payment Amount” but it gives me an error whenever I try to do that
 
Can you click "Copy Details" and then paste the text here in CODE TAGS.
 
System.ArgumentException
HResult=0x80070057
Message=Delegate to an instance method cannot have null 'this'.
Source=mscorlib
StackTrace:
at System.MulticastDelegate.CtorClosed(Object target, IntPtr methodPtr)
at Pay_Calculator.JUDGPAYCALC.InitializeComponent() in C:\Users\agregware\source\repos\Pay_Calculator\Pay_Calculator\Form1.Designer.cs:line 203
at Pay_Calculator.JUDGPAYCALC..ctor() in C:\Users\agregware\source\repos\Pay_Calculator\Pay_Calculator\Form1.cs:line 18
at Pay_Calculator.Program.Main() in C:\Users\agregware\source\repos\Pay_Calculator\Pay_Calculator\Program.cs:line 19
 

Latest posts

Back
Top Bottom