简体   繁体   中英

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);
        }
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM