Windows フォームの ErrorProvider コンポーネントを使用すると、ユーザーが無効なデータを入力したときに、エラー アイコンを表示できます。タブでフォーカスを移動して妥当性検査のコードを呼び出すには、フォーム上に少なくとも 2 つのコントロールが必要です。
コントロールの値が無効の場合にエラー アイコンを表示するには
-
Windows フォームにテキスト ボックスなどのコントロールを 2 つ追加します。
-
フォームに ErrorProvider コンポーネントを追加します。
-
1 番目のコントロールを選択し、そのコントロールの Validating イベント ハンドラにコードを追加します。このコードを正しく実行するには、イベントにプロシージャを関連付ける必要があります。詳細については、「方法 : Windows フォームで実行時にイベント ハンドラを作成する」を参照してください。
ユーザーが入力したデータの妥当性を検査するコードの例を次に示します。データが無効の場合は、SetError メソッドが呼び出されます。SetError メソッドの 1 番目の引数は、隣にアイコンを表示するコントロールを指定します。2 番目の引数は、表示するエラー テキストです。
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 e)
{
errorProvider1.SetError(textBox1, "Not an integer value.");
}
}
protected void textBox1_Validating(Object sender, CancelEventArgs e)
{
try
{
int x = Int32.Parse(textBox1.get_Text());
errorProvider1.SetError(textBox1, "");
}
catch(Exception exp)
{
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);
-
プロジェクトを実行します。無効なデータ (上の例では、数値以外のデータ) を 1 番目のコントロールに入力し、タブで 2 番目のコントロールに移動します。エラー アイコンが表示されたら、マウス ポインタでアイコンをポイントし、エラー テキストを表示します。
参照