1

検証済みイベントがテキストボックスでどのように機能するかは理解していますが、フォームのボタンでどのようにトリガーされるかはわかりません。

MSDN のドキュメントには、検証済み/検証中のリストがありません。

ただし、両方のプロパティがプロパティ ウィンドウにイベントとして表示されます。 ここに画像の説明を入力

4

3 に答える 3

4

MSDN の間違ったドキュメント ページにアクセスしています。Button Eventsを通過する必要があります。 ValidatedおよびValidatingイベントに関するヘルプが見つかります。

から派生した各Controlオブジェクトには、 と という名前の 2 つのイベントがValidatingあり Validatedます。という性質も持っていますCausesValidation。これが true に設定されている場合 (デフォルトでは true)、コントロールは検証に参加します。それ以外の場合は、そうではありません。

例:

private void textBox1_Validating(object sender, 
                System.ComponentModel.CancelEventArgs e)
{
   string errorMsg;
   if(!ValidEmailAddress(textBox1.Text, out errorMsg))
   {
      // Cancel the event and select the text to be corrected by the user.
      e.Cancel = true;
      textBox1.Select(0, textBox1.Text.Length);

      // Set the ErrorProvider error with the text to display.  
      this.errorProvider1.SetError(textBox1, errorMsg);
   }
}

private void textBox1_Validated(object sender, System.EventArgs e)
{
   // If all conditions have been met, clear the ErrorProvider of errors.
   errorProvider1.SetError(textBox1, "");
}
public bool ValidEmailAddress(string emailAddress, out string errorMessage)
{
   // Confirm that the e-mail address string is not empty. 
   if(emailAddress.Length == 0)
   {
      errorMessage = "e-mail address is required.";
         return false;
   }

   // Confirm that there is an "@" and a "." in the e-mail address, and in the correct order.
   if(emailAddress.IndexOf("@") > -1)
   {
      if(emailAddress.IndexOf(".", emailAddress.IndexOf("@") ) > emailAddress.IndexOf("@") )
      {
         errorMessage = "";
         return true;
      }
   }

   errorMessage = "e-mail address must be valid e-mail address format.\n" +
      "For example 'someone@example.com' ";
      return false;
}

編集:
ソース:

WinForms での検証の最大の問題は、コントロールが「フォーカスを失った」場合にのみ検証が実行されることです。そのため、ユーザーは実際にテキスト ボックス内をクリックしてから、別の場所をクリックして検証ルーチンを実行する必要があります。入力されたデータが正しいことのみを気にする場合は、これで問題ありません。しかし、ユーザーがスキップしてテキストボックスを空のままにしていないことを確認しようとしている場合、これはうまく機能しません。

私のソリューションでは、ユーザーがフォームの送信ボタンをクリックすると、フォーム (または指定されたコンテナー) の各コントロールをチェックし、リフレクションを使用して、コントロールに検証メソッドが定義されているかどうかを判断します。そうである場合、検証メソッドが実行されます。いずれかの検証が失敗した場合、ルーチンは失敗を返し、プロセスを停止できます。このソリューションは、検証するフォームが複数ある場合に特に有効です。

参考文献:
WinForm UI Validation
C# winforms のテキストボックスの入力を検証する

于 2013-04-11T13:46:42.383 に答える