簡體   English   中英

必填字段為空時如何取消按鈕單擊動作?

[英]How to cancel Button click action when required fields are empty?

我有兩種形式的程序。 其中一個檢查空字段,第二個插入記錄。

private void CheckNullValues()
{
    if (textBox1.Text == "") { 
        MessageBox.Show("Field [Email] can not be empty","Information",MessageBoxButtons.OK, MessageBoxIcon.Information);
        textBox1.Focus();
        return();
    }
}

private void buttonAdd_Click(object sender, EventArgs e)
{
     CheckNullValues();
     MessageBox.Show("Insert record");
}

如果textBox1為空並且不讓其顯示MessageBox.Show("Insert record")如何停止執行CheckNullValues過程中的操作?

您需要將CheckNullValues方法的類型更改為bool ,以便根據TextBox是否為空而返回true或false值。

您可能還想將其名稱更改為反映返回值的名稱。 我通常使用這樣的東西:

private bool ValidInputs()
{
    if (string.IsNullOrEmpty(textBox1.Text))
    { 
        MessageBox.Show("Field [Email] can not be empty","Information", 
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
        textBox1.Focus();
        return false;
    }
    if (string.IsNullOrEmpty(textBox2.Text))
    { 
        // ...
        return false;
    }

    return true;
}

然后,在您的按鈕單擊事件中,您可以輕松地執行以下操作:

if (!ValidInputs()) return;

此外,為避免在ValidInputs()方法中重復代碼,可以將用於驗證TextBox內容的邏輯移到單獨的方法中:

public bool TextBoxEmpty(TextBox txtBox, string displayMsg)
{
    if (string.IsNullOrEmpty(txtBox.Text)) 
    { 
        MessageBox.Show(displayMsg, "Required field", 
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
        txtBox.Focus();
        return true;
    }

    return false;
}

這樣,您的ValidInputs()方法將變為:

private bool ValidInputs()
{
    if (TextBoxEmpty(textBox1, "Field [Email] can not be empty")) return false;
    if (TextBoxEmpty(textBox2, "Some other message")) return false;
    // ...

    return true;
}

如果將檢查某物是否為null的函數設置為返回true或false,則可以在click事件中使用if語句。

if (!checkForNulls()) {
    MessageBox.Show("Insert record");
}

請按如下所示修改您的代碼:private bool CheckNullValues(){

        if (textBox1.Text == "")
        {
            MessageBox.Show("Field [Email] can not be empty", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            textBox1.Focus();
            return false;
        }
        else
        {
            return true;
        }
    }

    private void buttonAdd_Click(object sender, EventArgs e)
    {
        if (CheckNullValues())
        {
            MessageBox.Show("Insert record");
        }       
    }

暫無
暫無

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

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