DataGridView: Binding no-nullable values and adding new row

Posts   
 
    
Sokon1
User
Posts: 97
Joined: 17-Jul-2006
# Posted on: 25-Oct-2006 15:29:13   

Using V2.0.0.0, self servicing scenario, and vs2005.

Situation: - Database table with a not nullable foreign key field. - The related entity's fields holding the foreign key values are also not nullable (logical) - I bind a collection of those entities to a datagrid - The datagrid's column, which shows the foreign key, is a DataGridViewComboBox, filled with all possible values. - The grid's property 'AllowUserToAddRows' is set to 'true' - Now, try to click into the last (new) line in the grid during run time

The following messagebox occurs:

The following exception occurred in the DataGridView: System.ArgumentException: DataGridViewComboBoxCell value is not valid. To replace this default dialog please handle the DataError event.

This is, as i found out, because the DataSource of the Grid, which ist a EntityCollection, doesn't allow null values in the fk-field, and the grid tries to do that when entering the last row. I tried to prevent the grid from doing this, but didn't succeed.

Is the only possible solution to add the new line by code an set the 'AllowUserToAddRows' property to false? Does anybody have an suggestion, how to do this in the way i tried as described above?

Thanks in advance!

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 25-Oct-2006 17:21:37   

I think you might try using the DefaultValuesNeeded event of the DataGridView to set default values for the FK field, so it can be binded to an item in the associated comboBox.

VB Example

Private Sub dataGridView1_DefaultValuesNeeded(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) _
    Handles dataGridView1.DefaultValuesNeeded

    With e.Row
        .Cells("City").Value = "Redmond"
    End With

End Sub

C# Example

private void dataGridView1_DefaultValuesNeeded(object sender,
    System.Windows.Forms.DataGridViewRowEventArgs e)
{
    e.Row.Cells["City"].Value = "Redmond";
}