views:

525

answers:

3

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. Value '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!

A: 

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

Joel Coehoorn
I'm not sure I fully grasp this. I am creating a datatable as my source that I populate manually. How would I get to the OnSelected event?
ErocM
Don't worry about it: I was thinking asp.net, but DataGridView is a winforms control. So this doesn't really apply to you. I'll leave it up rather than deleting it to help anyone else avoid the same mistake.
Joel Coehoorn
+1  A: 

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."

Wim Hollebrandse
Can you tell me what event I am capturing this on?
ErocM
A: 

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.

Meta-Knight