[整理] 在DataGrid中引发验证
Causesvalidation In Datagrid
在我们对Datagrid进行编辑的时候,我们可能要对用户输入的数据进行验证,以确保数据的正确性、完整性。要解决这个问题有很多不同的方法,如:我们可以运用当中的验证控件,如: RequiredFieldValidator 。这样我们便需要 DataGrid中的 Update 按钮引发验证来检验用户输入的数据是否为空。Update 按钮包含一个CausesValidation 属性。
我们可以利用这个属性来自由控制一个webcontrol是否引发验证。
DataGrid ItemDataBound 事件:
If (e.Item.ItemType = ListItemType.EditItem) Then
setUpdateCommandCausesValidation(e.Item, True)
End If
Private Function setUpdateCommandCausesValidation(ByVal item As DataGridItem, ByVal valor As Boolean) As String
If (item.HasControls()) Then
For Each celula As Control In item.Controls
For Each possibleButton As Control In celula.Controls
If (possibleButton.GetType().Name.Equals("DataGridLinkButton")) Then
Dim lbt As LinkButton = CType(possibleButton, LinkButton)
If (lbt.Text.Equals(getUpdateColumnText())) Then
lbt.CausesValidation = valor
Exit For
End If
End If
Next
Next
End If
End Function
Private Function getUpdateColumnText() As String
Dim text As String = ""
For Each coluna As DataGridColumn In DataGrid1.Columns
If (coluna.GetType().Name.Equals("EditCommandColumn")) Then
Dim colunaEdit As EditCommandColumn = CType(coluna, EditCommandColumn)
text = colunaEdit.UpdateText
Exit For
End If
Next
Return text
End Function