0

ねえ、私はすべてのコードを機能させて、それは大丈夫です。でも少し片付けたいです。

現時点では、入力にエラーがあるかどうかを示すメッセージボックスが表示されているので、「入力を確認してください」と表示されますが、「次の名前を確認してください:名、秒名など」のように表示したいと思います。 。」

if  ((FirstnameText.Text.Trim().Length == 0) || (SurnameText.Text.Trim().Length == 0)
    || (DateOfBirthText.Text.Trim().Length == 0) || (CourseText.Text.Trim().Length == 0)
    || (MatricNoText.Text.Trim().Length == 0) || (YearMarkText.Text.Trim().Length == 0)
    || (int.Parse(MatricNoText.Text) < 10000 || int.Parse(MatricNoText.Text) > 99999)
    || (int.Parse(YearMarkText.Text) < 0 ||  int.Parse(YearMarkText.Text) > 100))

   {
      errorMessage();
      return;
   }

public void errorMessage()
{
   MessageBox.Show("Please check your input");
}

散らかっていることは知っていますが、うまくいきます

現在、そのメッセージを出力するだけですが、エラーのある特定のテキストボックスを出力する簡単な方法はありますか?

ありがとう

4

4 に答える 4

2

組み込みのErrorProviderコンポーネントは、状況に応じて驚異的に機能します。ツールボックスからフォームのデザイナにドラッグします。下部に表示され、NotificationIconsとContextMenuStripsが表示されます。ErrorProviderの優れている点は、コントロールの横にあるツールチップの上にマウスを置くと、視覚的なフィードバックアイコンが表示されることです。

次に、コントロールの「検証」イベントを使用して、必要なものを確認できます。

private void FirstnameText_Validating (object sender, CancelEventArgs e)
{
    string error = null;

    if (FirstnameText.Text.Length == 0)
    {
        error = "You must enter a First Name";
        e.Cancel = true; // This is important to keep focus in the box until the error is resolved.
    }

    ErrorProvider.SetError((Control)sender, error); // FirstnameText instead of sender to avoid unboxing the object if you care that much
}

「検証中」イベントで発生させる代わりに、保存ボタンに貼り付けることもできます。コードをさらにクリーンアップするには、入力を検証するクラスを作成して、UI以外のものをUIから除外します。

于 2012-10-18T14:38:07.487 に答える
1

コードを分割することから始めます。

if  ((FirstnameText.Text.Trim().Length == 0){
   errorMessage("firstname is empty");
}

if (SurnameText.Text.Trim().Length == 0){
   errorMessage("surname is empty");
}

アイデアが浮かびますか?

于 2012-10-18T12:39:58.570 に答える
0

可能であれば、以下のようにコードを書き直してください

Control errorControl =null;
foreach (Control ctrl in this.Controls)
{
  if (ctrl is TextBox)
  {
    if (ctrl.Name == "MatricNoText")
    {
      if ((int.Parse(MatricNoText.Text) < 10000 || int.Parse(MatricNoText.Text) > 99999))
          {
            errorControl = ctrl;
          }
     }
     else if (ctrl.Name == "MatricNoText")
     {
       if (int.Parse(YearMarkText.Text) < 0 || int.Parse(YearMarkText.Text) > 100)
       {
         errorControl = ctrl;
        }
      }
      else
      {
        if (ctrl.Text.Length == 0)
        {
          errorControl = ctrl;
         }
       }
    }
  }

MessageBox.Show("Please check your input." + errorControl.Focus());
于 2012-10-18T12:45:59.743 に答える
0

私はよくFluentValidationを使用します。このWithMessageメソッドでは、エラーメッセージを指定できます。次に、バリデーターはすべてのエラーメッセージの列挙可能なものを返します。特定の問題に適した方法もあるかもしれません。

于 2012-10-18T12:50:10.347 に答える