john
john

Reputation: 23

Validate to ensure that text has been entered in a text box before pressing a button that moves them to a new form

I have a text box called txtName and a button called btnPlay. How do i ensure that they can't press the play button and play the game without entering their name. The players name is then stored in a text file

   private void button1_Click(object sender, EventArgs e)
    {

        File.AppendAllText(@"..\..\..\Files\playerdetails.txt", txtName.Text);
        {
            MessageBox.Show("You are now ready to play");
            Form1 myForm1 = new Form1();
            myForm1.Show();
        }

Upvotes: 0

Views: 46

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39122

Just check it in the button handler:

 private void button1_Click(object sender, EventArgs e)
{
    if (txtName.Text.Length == 0)
    {
        MessageBox.Show("Please enter a name!");
        return;
    }
    File.AppendAllText(@"..\..\..\Files\playerdetails.txt", txtName.Text);
    MessageBox.Show("You are now ready to play");
    Form1 myForm1 = new Form1();
    myForm1.Show();
}

Upvotes: 0

Roy John
Roy John

Reputation: 29

Add the below lines too

 private void textBox1_TextChanged(object sender, EventArgs e)
 {
    button1.Enabled = textBox1.Text.Length > 0;
 }

Upvotes: 1

Related Questions