-1

I am trying to handle an exception but I'm confused about how I do it. Here is my code

modules.Add(new Modules() { 
name = namebox.Text, 
code = codebox.Text, 
credits = Convert.ToInt32(creditbox.Text), 
hours = Convert.ToInt32(hoursbox.Text),
date = semesterbox.Text, 
weeks = Convert.ToInt32(semesterweekbox.Text), 
studyhours = m1.Calculations(Convert.ToInt32(hoursbox.Text), Convert.ToInt32(semesterweekbox.Text), Convert.ToInt32(creditbox.Text))
});

I'm trying to handle this exception so it does end my code if I do not input values in the textboxes. From the research I've done, I found out that the ToInt32 line might be the issue. Some coders suggested I use the tryparse function. How would I use that function to handle this error?

Exception Thrown

  • can you post the exception as well, that will help a lot. – Noorul Sep 17 '21 at 10:54
  • I added an image that shows the exception hope that helps – DekluitTheNoob Sep 17 '21 at 11:00
  • If, instead of working directly with UI elements, you use Bindings (as is customary for WPF), then you will not need a "manual" conversion and, accordingly, there will be no exceptions. Learn how to work properly with WPF and you will greatly facilitate your work. – EldHasp Sep 17 '21 at 11:17
  • When faced with a problem like this, it is always easiest if you do all the converting into separate variables one at a time. That way you can step through the code line by line to check on which value it fails. It would then be a simple matter to check wht the text value is, which causes the error. – Jonathan Willcock Sep 17 '21 at 11:18

1 Answers1

0

A System.FormatException happens when you want to "parse" a string to another type, like an integer, that makes a number in text be represented as a real number, in your case, you are calling Convert.ToInt32, be sure that whatever string being passed as argument to this method, don't overflow the capabilities of the Int32 struct, or that the text does not contain letters or decimal points. If that is the case, to verify if a number is valid use int.TryParse, it will only return true if the text is in a correct format like so:

if (int.TryParse("5", out int number))
{
    // Do something with that number
}

Here, if "5" is not a number, the if block will be completely skipped.