开发者

Vb.Net Datagridview Error Handling

I have a datagridview that seems to be working fine until the user adds a name into the unique name column that already exists.

I am getting this:

System.Data.ConstraintException: Column 'Name' is constrained to be unique. Va开发者_JS百科lue 'test' is already present.

Any suggests as to where and how I capture this error and prevent the users from adding another name, case insensitive, to prevent this huge error from coming up?

Thanks!


Just catch exceptions of type ConstraintException in your code (make sure it's around the bit where you perform the insert). If that exception gets caught, you display some friendly text "The name 'test' already exists. Please choose another name."


Look in your data source's OnSelected event, specifically the Exception and ExceptionHandled properties of the event arguments.


You could simply handled the CellValidating event and check if an item with the same name exits. If it exists, set e.Cancel to True and set an error message on this row. Example:

Private Sub dataGridView1_CellValidating(ByVal sender As Object, _
                                         ByVal e As DataGridViewCellValidatingEventArgs) _
                                         Handles dataGridView1.CellValidating

    If ExistsItemWithName(e.FormattedValue.ToString) Then
        e.Cancel = True
        Me.dataGridView1.Rows(e.RowIndex).ErrorText = "An item with this name already exists"
    End If

End Sub

Note that if you set an ErrorText in CellValidating, you should also handle CellValidating to set back the ErrorText to String.Empty.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜