Reputation: 936
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;
}
}
}
Upvotes: 2
Views: 550
Reputation: 3582
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);
Upvotes: 5