James Dylan
James Dylan

Reputation: 11

Newbie - How to prompt for user input in C#

I'm in the second week of C#, enjoying it. I am doing an extra credit quiz, have one issue I can't seem to figure out.

The user is supposed to enter their name into a textbox, when submit is pressed, it will display the name in a messagebox. Easy. But my problem is, I am supposed to have it display a message box if the input field is blank, displaying "Please enter your name!" I cannot find it anywhere in the book, or online. All I have (related to this button) so far is below, but I know it isn't right. As it is, it simply opens both windows, lol. Any help for a newbie? lol

    private void Submit_Click(object sender, EventArgs e)
    {
        if (textBoxName.Text == "")
        {
            MessageBox.Show("Please Enter Your Name");
        }
        {
            MessageBox.Show("Hello, " + this.textBoxName.Text);
        }
    }

Upvotes: 1

Views: 1248

Answers (1)

Mohsen Kamrani
Mohsen Kamrani

Reputation: 7457

Just use an else:

   private void Submit_Click(object sender, EventArgs e)
    {
        if (textBoxName.Text == "")
        {
            MessageBox.Show("Please Enter Your Name");
        }
        else
        {
            MessageBox.Show("Hello, " + this.textBoxName.Text);
        }
    }

By the way, for single statement if/else block you don't need curly braces.

Upvotes: 2

Related Questions