Aggiunta e lettura di informazioni sugli errori delle righe

Per evitare di rispondere a ogni errore di riga che si verifica durante la modifica dei valori in una DataTable, è possibile aggiungere alla riga le informazioni sugli errori, da utilizzare in un secondo momento. L'oggetto DataRow supporta questa funzionalità fornendo una proprietà RowError per ogni riga. L'aggiunta di dati alla proprietà RowError di un DataRow consente di contrassegnare la proprietà HasErrors di DataRow come true. Se il DataRow fa parte di una DataTable e il valore per DataRow.HasErrors è true, anche il valore per la proprietà DataTable.HasErrors sarà true. Queste impostazioni si applicano anche al DataSet a cui appartiene la DataTable. Quando si effettuano verifiche relative agli errori, è possibile controllare la proprietà HasErrors per stabilire se alle righe sono state aggiunte informazioni relative agli errori. Se il valore per HasErrors è true, è possibile utilizzare il metodo GetErrors della DataTable per restituire ed esaminare solo le righe contenenti errori, come mostrato nell'esempio seguente.

Dim workTable As DataTable = New DataTable("Customers")
workTable.Columns.Add("CustID", Type.GetType("System.Int32"))
workTable.Columns.Add("Total", Type.GetType("System.Double"))

AddHandler workTable.RowChanged, New DataRowChangeEventHandler(AddressOf OnRowChanged)

Dim I As Int32

For I = 0 To 10
  workTable.Rows.Add(New Object() {I, I*100})
Next

If workTable.HasErrors Then
  Console.WriteLine("Errors In Table " & workTable.TableName)

  Dim myRow As DataRow

  For Each myRow In workTable.GetErrors()
    Console.WriteLine("CustID = " & myRow("CustID").ToString())
    Console.WriteLine(" Error = " & myRow.RowError & vbCrLf)
  Next
End If

Private Shared Sub OnRowChanged(sender As Object, args As DataRowChangeEventArgs)
  ' Check for zero values.
  If CDbl(args.Row("Total")) = 0 Then args.Row.RowError = "Total cannot be 0."
End Sub
[C#]
DataTable  workTable = new DataTable("Customers");
workTable.Columns.Add("CustID", typeof(Int32));
workTable.Columns.Add("Total", typeof(Double));

workTable.RowChanged += new DataRowChangeEventHandler(OnRowChanged);

for (int i = 0; i < 10; i++)
  workTable.Rows.Add(new Object[] {i, i*100});

if (workTable.HasErrors)
{
  Console.WriteLine("Errors In Table " + workTable.TableName);

  foreach (DataRow myRow in workTable.GetErrors())
  {
    Console.WriteLine("CustID = " + myRow["CustID"]);
    Console.WriteLine(" Error = " + myRow.RowError + "\n");
  }
}

protected static void OnRowChanged(Object sender, DataRowChangeEventArgs args)
{
  // Check for zero values.
  if (args.Row["Total"].Equals(0D))
    args.Row.RowError = "Total cannot be 0.";
}

Vedere anche

Modifica dei dati in una DataTable | Classe DataColumnCollection | Classe DataRow | Classe DataTable