I created a guessing game application. When the user enters a letter it crashes. I want the textbox to only have integers. I was trying to create a validation so when the user enters a letter it will display a message only integers only. How can I add a validation to the program so where the user can only enter an integer?
I tried using this code but it still crashes:
double input = Convert.ToInt32(txtInput.Text);
if (Double.TryParse(txtInput.Text, out input))
{
txtInput.Text = Convert.ToString(input);
}
else
{
MessageBox.Show("Please enter a valid number.");
}
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 WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double guess;
private void Form1_Load(object sender, EventArgs e)
{
Random rand = new Random();
guess = rand.Next(1, 101);
}
private void Clickbutton_click(object sender, EventArgs e)
{
double input = Convert.ToInt32(txtInput.Text);
if (Double.TryParse(txtInput.Text, out input))
{
txtInput.Text = Convert.ToString(input);
}
else
{
MessageBox.Show("Please enter a valid number.");
}
if (input == guess)
{
lblMessage.Text = "You Are Corrrect, You Win" + " " +
" \r\n Random Number was = " + Convert.ToString(guess);
}
else if (input > guess)
{
lblMessage.Text = "Number is too High, Try Again";
txtInput.Clear();
}
else if (input < guess)
{
lblMessage.Text = "Number is too Low, Try Again";
txtInput.Clear();
}
}
}
}