2016-12-15 44 views
0

私はいくつかの行と列で構成されるDataGridViewを持っています。空のセルのDataGridViewのすべてのセルをチェックしたい場合は、いずれかのセルが空であれば、それからメッセージを与えます。私はそれを行うためのコードを持っていますが、それは最初の行 の細胞のみをチェックする。これは私のコードです:すべてのdatagridviewセルを検証する方法は?

代わりに細胞の
foreach (DataGridViewRow rw in dgv_absence.Rows) 
    { 
     if (rw.Cells[0].Value == null || rw.Cells[0].Value == DBNull.Value || string.IsNullOrWhiteSpace(rw.Cells[0].FormattedValue.ToString()) || rw.Cells[1].Value == null || rw.Cells[1].Value == DBNull.Value || string.IsNullOrWhiteSpace(rw.Cells[1].FormattedValue.ToString())) 
     { 
      MessageBox.Show("message","title"); 
      return; 
     } 
     else 
     { 
      for (int i = 0; i < dgv_absence.Rows.Count - 1; i++) 
      { 
       // do some thing 
      } 
     } 
    } 
+0

これはWindowsフォームアプリケーションの場合ですか? –

+2

いくつかの検証イベントがあります。すべての行をループすると効率的ではありません。 – Plutonix

+0

はい、Windowsフォーム –

答えて

0

[0]、唯一の各行の最初のセルを対象とした、あなたがする必要があります内側forループ内のセルをループします。

 foreach (DataGridViewRow row in dataGridView.Rows) 
     { 
      foreach (DataGridViewCell cell in row.Cells) 
      { 

      } 
     } 
+0

okそれをどうやって入力すればいいですか? –

+0

@ honar.cs、私はコードスニペットを編集しました。 – Forklift

+0

エラー.Cellsの定義はありませんか? –

0

使用すると、1個のセルが空であるかどうか、それは返すこのメソッドを呼び出すことができます:このようにこれは私がどうなるかである

if (!IsDataGridViewEmpty(dgv_absence)) 
     { 
      MessageBox.Show("message","title"); 
      return; 
     } 
+0

これは、OPが入力中にデータを検証しようとしている場合にのみ便利だと思います。 –

+0

この方法は有用ではありません。私は、データグリッドビューを含むフォーム上にあるボタンを押したときにセルを検証したいと思っています。 –

+0

私はセルが空であるかどうかをテストする方法で自分の答えを編集しています。 –

0

public Boolean IsDataGridViewEmpty(DataGridView dataGridView) 
    { 
     bool isEmpty = false; 
     foreach (DataGridViewRow row in dataGridView.Rows) 
     { 
      if (!row.IsNewRow) 
      { 
       foreach (DataGridViewCell cell in row.Cells) 
       { 
        //if (!string.IsNullOrEmpty(cell.Value.ToString())) 
        //{ 
        if (string.IsNullOrEmpty(cell.Value.ToString().Trim())) 
        { 
         isEmpty = true; 
         break; // TODO: might not be correct. Was : Exit For 
         // } 
        } 
       } 
      } 
     } 
     return isEmpty; 
    } 

次の方法でそれを呼び出すことができます行う。

MSDNが言うように、WindowsフォームでのDataGridコントロールがIDataErrorInfo

を実装するオブジェクトからのエラーを読み取ることができます。

IDataErrorInfoユーザーインターフェイスがバインドできるカスタムエラー情報を提供する機能を提供します。

public class MyEntity : IDataErrorInfo 
{ 
    public string this[string columnName] 
    { 
     get 
     { 
      // here you can validate each property of your class (POCO object) 
      var result = string.Join(Environment.NewLine, Validator.Validate(this, columnName).Select(x => x.ErrorMessage)); 
      return result; 
     } 
    } 

    public string Error 
    { 
     get 
     { 
      // here you can errors related to the whole object (ex: Password, and PasswordConfirmation do not match) 
      return string.Join(Environment.NewLine, Validator.Validate(this) 
                   .Select(x => x.ErrorMessage)); 
     } 
    } 

    public Boolean IsValid 
    { 
     get { return string.IsNullOrEmpty(Error); } 
    } 
} 

次に、あなたがあなたの検証ルールを設定するには、いくつかの検証技術を使用することができます。

グリッドのデータソースのコレクション内のあなたのPOCOオブジェクト、IDataErrorInfoはのは、このような何かを言わせて実装する必要があります。

私はDataAnnotationを使用して検証ロジックを実装したいと思います。だから、

、あなたのクラスは可能性がnullにすることはできませんというのは、あなたのクラスは、プロパティ(名前を)持っているとしましょう:あなたはこの

public class Validator : IValidator 
{ 
    public IEnumerable<ErrorInfo> Validate(object instance) 
    { 
     IEnumerable<ErrorInfo> errores = from property in instance.GetType().GetProperties() 
      from error in GetValidationErrors(instance, property) 
      select error; 
     if (!errores.Any()) 
     { 
      errores = from val in instance.GetAttributes<ValidationAttribute>(true) 
       where 
        val.GetValidationResult(null, new ValidationContext(instance, null, null)) != 
        ValidationResult.Success 
       select 
        new ErrorInfo(null, 
         val.GetValidationResult(null, new ValidationContext(instance, null, null)).ErrorMessage, 
         instance); 
     } 

     return errores; 
    } 

    public IEnumerable<ErrorInfo> Validate(object instance, string propertyName) 
    { 
     PropertyInfo property = instance.GetType().GetProperty(propertyName); 
     return GetValidationErrors(instance, property); 
    } 

    private IEnumerable<ErrorInfo> GetValidationErrors(object instance, PropertyInfo property) 
    { 
     var context = new ValidationContext(instance, null, null); 
     context.MemberName = property.Name; 
     IEnumerable<ErrorInfo> validators = from attribute in property.GetAttributes<ValidationAttribute>(true) 
      where 
       attribute.GetValidationResult(property.GetValue(instance, null), context) != 
       ValidationResult.Success 
      select new ErrorInfo(
       property.Name, 
       attribute.FormatErrorMessage(property.Name), 
       instance 
       ); 

     return validators.OfType<ErrorInfo>(); 
    } 
} 

ようなエラーがバリデータを使用している場合だろうその後

public class MyEntity : IDataErrorInfo 
{ 
    [Required] 
    public string Name { get; set; } 

    public string this[string columnName] 
    { 
     get 
     { 
      // here you can validate each property of your class (POCO object) 
      var result = string.Join(Environment.NewLine, Validator.Validate(this, columnName).Select(x => x.ErrorMessage)); 
      return result; 
     } 
    } 

    public string Error 
    { 
     get 
     { 
      // here you can validate errors related to the whole object (ex: Password, and PasswordConfirmation do not match) 
      return string.Join(Environment.NewLine, Validator.Validate(this) 
                   .Select(x => x.ErrorMessage) 
                   .Union(ModelError.Select(m => m.Value))); 
     } 
    } 

    public Boolean IsValid 
    { 
     get { return string.IsNullOrEmpty(Error); } 
    } 
} 

エラーに応じてセルごとまたは行ごとにグリッドに表示されます。

オブジェクトのインライン編集を計画している場合は、INotifyPropertyChangedも実装する必要があります。

この手法は、検証ロジックをユーザーインターフェイスから切り離すという利点があります。

+0

Fluent Validationを使用できるようにするには、私の回答をここで確認してください。http://stackoverflow.com/a/40997368/819153このようにして、別のプロジェクトで検証を行います。どこでも、Windowsフォーム、Xamarin、Asp.Netを使用することができます – Zinov

関連する問題