簡體   English   中英

MessageBox 出現三次后如何關閉表單?

[英]How to close form after MessageBox shows up three times?

所以我開始編寫這個簡單的代碼,它會要求一個名字,只有“adam”可以工作,其他任何事情都不會。 但我希望它在三次嘗試失敗后關閉表單

private void button2_Click(object sender, EventArgs e) {
     int Counter = 0;

     if (textBox1.Text == "adam"){
         MessageBox.Show("hello, " + textBox1.Text);
     } else if (textBox1.Text != "adam"){
         MessageBox.Show("Please write the correct name. As " + textBox1.Text + " is not correct");
         Counter++;
     } else if (Counter ==3){
         this.Close();
     }

我嘗試過“else if”語句和“If”,但似乎沒有任何效果

您的if (textBox1.Text == "adam")else if (textBox1.Text != "adam")將始終為真; 用戶要么寫了,要么沒有寫,“亞當”在他的盒子里。 這意味着要么輸入if ,要么輸入第一個else if

你的代碼永遠不會檢查else if (Counter ==3)因為它總是會更快地找到正確的東西

也許您應該斷開if(Counter檢查與其他檢查的連接(刪除else並使其成為自己的if ):

    if (textBox1.Text == "adam")
    {
        MessageBox.Show("hello, " + textBox1.Text);
    }
    else if (textBox1.Text != "adam")
    {
        MessageBox.Show("Please write the correct name. As " + textBox1.Text + " is not correct");
        Counter++;
    }
  
    if (Counter ==3)
    {
        this.Close();
    }

而且,不要在button2_Click中聲明Counter在 class 中聲明它:

public class YourFormNameHere: Form{

  public int Counter {get;set;} = 0;

  ...

旁注:C# 的命名約定; 如果在一個方法中聲明(就像你現在擁有的那樣),它應該被稱為int counter = 0 如果它位於 class 的頂部並且是公共的,則將其稱為Counter ,如果它是私有的或受保護的,則將其稱為_counter 如果它是公開的,請將其設為屬性( get;set; ),而不是字段


編輯:

這是整個事情的樣子:

public class YOUR_CLASS_NAME_HERE: Form{

    public int Counter {get;set;} = 0;

    private void button2_Click(object sender, EventArgs e) {

        if (textBox1.Text == "adam")
        {
            MessageBox.Show("hello, " + textBox1.Text);
        }
        else if (textBox1.Text != "adam")
        {
            MessageBox.Show("Please write the correct name. As " + textBox1.Text + " is not correct");
            Counter++;
        }
      
        if (Counter ==3)
        {
            this.Close();
        }
    }
}

實際上,它還應該為變量使用有用的名稱,例如usernameTextBoxLoginButton_Click - 將控件放在表單上后,請務必花時間重命名控件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM