2

what i am attempting to do is, get user input from a text box, convert it to an int and then use that. i got everything to work except the the try and catch. incase the person puts a letter instead of a number. with the code below it always catches something. i have no idea what is catches something. i've taken out the bool test and if i put in a letter it will just throw the exception then go to the beeping. other then waiting for a valid input. please excuse my messy code, i am still a beginner c# programmer :D thanks in advanced!

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication4 { public partial class Form1 : Form { bool tone = false; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { bool test = true; speedInput.Clear(); beep.Clear(); int beepspeed = 90; int speed = 100; string speedtext = this.speedInput.Text; string beeptext = this.beep.Text; try { test = true; beepspeed = Convert.ToInt32(beeptext); speed = Convert.ToInt32(speedtext); } catch (Exception) { MessageBox.Show("numbers above 37 only!!"); test = false; } if (test) { for (int i = 0; i < beepspeed; i++) { if (this.tone) { Random ran = new Random(); int rand = ran.Next(400, 3000); Console.Beep(rand, speed); } else { Console.Beep(1000, speed); } } } } private void radioButtonYes_CheckedChanged(object sender, EventArgs e) { this.tone = true; } private void radioButtonNo_CheckedChanged(object sender, EventArgs e) { this.tone = false; } } } 
2
  • 1
    As a beginner, I would and start with printing the exception. Commented Oct 25, 2013 at 23:51
  • 1
    Put a break point in the catch block, then when it hits the break point, put your mouse over the underline next to the word Exception. You should be able to pull up some exception details, the message and stacktrace would be great to post. Commented Oct 25, 2013 at 23:51

1 Answer 1

5

You are cleaning the content of the inputs at the beginning of the button1_click

speedInput.Clear(); beep.Clear(); 

Then when you try to convert empty string to int32 it fails

beepspeed = Convert.ToInt32(beeptext); speed = Convert.ToInt32(speedtext); 
Sign up to request clarification or add additional context in comments.

3 Comments

Terry Pratchett — 'Give a man a fire and he's warm for a day, but set fire to him and he's warm for the rest of his life
wow, i put that in for some testing, forgot about it.. then it comes back to bit me.. lol thanks for the fix :)
@JimW, Anonymous - 'Four eyes see more than two' :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.