Share via


如何:使用 Windows Form ErrorProvider 元件顯示表單驗證的錯誤圖示

當使用者輸入不正確資料時,您可以使用 Windows Forms ErrorProvider 元件來顯示錯誤圖示。 您必須在表單上至少有兩個控制項,才能在表單之間索引標籤,藉此叫用驗證碼。

當控制項的值無效時顯示錯誤圖示

  1. 將兩個控制項,例如文字方塊新增至 Windows Form。

  2. ErrorProvider將元件新增至表單。

  3. 選取第一個控制項,並將程式碼新增至其 Validating 事件處理常式。 為了讓此程式碼正常執行,程式必須連線到 事件。 如需詳細資訊,請參閱 如何:在 Windows Forms 執行時間建立事件處理常式。

    下列程式碼會測試使用者輸入的資料有效性;如果資料無效,則會 SetError 呼叫 方法。 方法的第一個引數 SetError 會指定要顯示旁邊圖示的控制項。 第二個引數是要顯示的錯誤文字。

    Private Sub TextBox1_Validating(ByVal Sender As Object, _  
       ByVal e As System.ComponentModel.CancelEventArgs) Handles _  
       TextBox1.Validating  
          If Not IsNumeric(TextBox1.Text) Then  
             ErrorProvider1.SetError(TextBox1, "Not a numeric value.")  
          Else  
             ' Clear the error.  
             ErrorProvider1.SetError(TextBox1, "")  
          End If  
    End Sub  
    
    protected void textBox1_Validating (object sender,  
       System.ComponentModel.CancelEventArgs e)  
    {  
       try  
       {  
          int x = Int32.Parse(textBox1.Text);  
          errorProvider1.SetError(textBox1, "");  
       }  
       catch (Exception ex)  
       {  
          errorProvider1.SetError(textBox1, "Not an integer value.");  
       }  
    }  
    
    private:  
       System::Void textBox1_Validating(System::Object ^  sender,  
          System::ComponentModel::CancelEventArgs ^  e)  
       {  
          try  
          {  
             int x = Int32::Parse(textBox1->Text);  
             errorProvider1->SetError(textBox1, "");  
          }  
          catch (System::Exception ^ ex)  
          {  
             errorProvider1->SetError(textBox1, "Not an integer value.");  
          }  
       }  
    

    (Visual C#、Visual C++)將下列程式碼放在表單的建構函式中,以註冊事件處理常式。

    this.textBox1.Validating += new  
    System.ComponentModel.CancelEventHandler(this.textBox1_Validating);  
    
    this->textBox1->Validating += gcnew  
       System::ComponentModel::CancelEventHandler  
       (this, &Form1::textBox1_Validating);  
    
  4. 執行專案。 在第一個控制項中輸入不正確 (在此範例中為非數值) 資料,然後將索引標籤移至第二個控制項。 顯示錯誤圖示時,請使用滑鼠指標指向它,以查看錯誤文字。

另請參閱