Pergunta

I have a datagridview bound to a datasource, column[0] AgencyName is a primary key and cannot be null. Clicking the Bindingnavigator ( + ) plus sign to add new row (twice) will result to error "Column (AgencyName) does not allow null". How to handle this null exception?

Overall can you show me how to handle null and primary key constraint in a datagridview bound to a datasource. Note that I just dragged a datasource into a winform to create this.

Form

I have this code

    private void clientsDataGridView_Validating(object sender, CancelEventArgs e)
    {

        DataGridViewRow row = clientsDataGridView.CurrentRow as DataGridViewRow;

        if (row.Cells[0].Value == DBNull.Value)
        {

           clientsDataGridView.CancelEdit();                
           e.Cancel = true;

        }
     }

this code wont let me navigate through the other records unless i provide a valid value. I want the new row (with invalid data) to be cancel whenever i move to the other rows

Foi útil?

Solução

From the Control.Validating Event Description (which DataGridView inherits from):

If the Cancel property of the CancelEventArgs is set to true in the Validating event delegate, all events that would usually occur after the Validating event are suppressed.

So by setting e.Cancel = true you're telling DataGridView to cancel all following events (including RowLeave).

You're using a Bindingsource and binding Datagridview to it? If so, I would try calling Bindingsource.CancelEdit() instead of Datagridview.CancelEdit().

Or perhaps:

Dim bm As BindingManagerBase = clientsDatagridView.BindingContext(clientsDatagridView.DataSource, clientsDatagridView.DataMember)
bm.CancelCurrentEdit()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top