0
votes

So, i have this datagridview that displays my whole table, as we all know the primary field cannot be empty or repeated, so i have to do some validating before saving it to the database.

i've managed to make my validation see that if i have an existing row and i change the primary key to an "empty" or a repeated value it locks the datagridview in that cell untill i fix it.

the problem comes in when i add a new row, if i dont focus the datagridview on the primary key the cell validating event does not fire and i get an error when i update the database because the datagrid accepts my empty value.

here's my attempt at the row validation but it does not work, i would like your help please. i want the row to be blocked until the user provides appropiate input to my primary key, the column is called "LOOPS" on index 5, however with the code i've posted it only triggers the lockdown if i step on the primary key!

private void dataGridView2_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
    {
        if (dataGridView2.Rows[e.RowIndex].Cells[5].ToString() == "")
        {
            dataGridView2.Rows[e.RowIndex].ErrorText = "El campo clave de la tabla (Loops) no puede estar en blanco";
            e.Cancel = true;
        }
    }
1

1 Answers

1
votes

just make sure the PK column is in read only and also, eventually, hidden so no user will edit it.

depending on your data access layer design ( the logic you use to load and update/insert data ), you can usually not pass any value for the PK field on insert and the database will generate one value for you ( if it is an integer auto increment ).

if you have still issues, show the way you are loading the data and binding the grid to the loaded data and also the way you are saving the changes back to the database.