2012-02-21 83 views
2

當在強類型DataTable上使用自動生成方法以編程方式添加新行時,如何激發驗證我的字段最大長度的自定義驗證?在添加新行時對DataTable進行驗證

我的客戶(C#)

DAL.ImportMarcDataSet.PublicationsRow newRow = importMarcDataSet.Publications.NewPublicationsRow(); 

newRow.CallNumber ="QA76.76.A65"; 
newRow.Title = "Programming WCF services"; 
newRow.ISBN = "0596526997"; 

importMarcDataSet.Publications.AddPublicationsRow(newRow); 

我的數據訪問層(VB)

Partial Class ImportMarcDataSet 
    Partial Class PublicationsDataTable 
     Private Sub CallNumberMaxLength(ByVal pRow As PublicationsRow) 
      If pRow.CallNumber.Length > 25 Then 
       pRow.SetColumnError("CallNumber", "The value entered is over the maximum length") 
      Else 
       pRow.SetColumnError("CallNumber", "") 
      End If 
     End Sub 
'this event is ok when user made changes to the CallNumber column of the current row 
     Private Sub PublicationsDataTable_ColumnChanged(ByVal sender As Object, ByVal e As System.Data.DataColumnChangeEventArgs) Handles Me.ColumnChanged 
      If e.Column Is Me.CallNumberColumn Then 
       CallNumberMaxLength(e.Row) 
      End If 
     End Sub 
    End Class 
End Class 

回答

1

您可以處理表的RowChanging事件。當DataRowChangeEventArgs.Action等於Add或其中一個更改...操作執行您的驗證。

自從我這樣做已經很長時間了,但我相信你甚至可以通過在DataRowChangeEventArgs.Row上調用CancelEdit來取消編輯。檢查文檔。請參閱處理DataTable事件(ADO.NET)http://msdn.microsoft.com/en-us/library/w9y9a401.aspx

TableNewRow不會幫助,因爲它只在調用NewRow時纔會產生。

+0

非常感謝。 – sovantha 2012-02-27 02:24:24

+0

在RowChanging事件中調用CancelEdit()將引發異常 - 請參見[link](http://msdn.microsoft.com/zh-cn/library/system.data.datarow.canceledit.aspx)。 RowChanging事件中必須拋出異常才能強制取消。只是想我會補充說,以防其他人來這個答案的幫助。 – Hagelt18 2013-05-30 19:28:46