Joe Joe - 22 hours ago 2
Vb.net Question

Adding value to DataGridView column when new record is created

I am using Visual Studio 2017/VB/Winforms and I have a

DataGridView
which is using a
BindingSource
to connect to an Access database.

It works well, but I need to programmatically add a value to one of the fields/columns which is hidden from the user when a new record is added. I'm quite sure this is a simple question, but I have been struggling with it for hours trying to figure out which event is the right one to use. Is it a
DataGridView
event I'm looking for or a
BindingSource
event?

Here is the code I thought would do the job, but it still gives me an error saying that ProjectID cannot be Null

Private Sub StoresDataGridView_DefaultValuesNeeded(sender As Object, e As DataGridViewRowEventArgs) _
Handles StoresDataGridView.DefaultValuesNeeded
e.Row.Cells("colProjectID").Value = 1
End Sub


Please help me figure this out, as again, I am sure it's something really simple that I'm missing. I also tried setting a break point in that event, and it doesn't even seem to be firing.

I also tried adding this to the form's Load event, and did not get any errors when the form loaded, but when trying to add a new record I still get the same error.

StoresDataGridView.Columns("colProjectID").DefaultCellStyle.NullValue = 1

Answer

Use the grid's RowValidating event like this:

StoresDataGridView.Rows(StoresDataGridView.Rows.Count - 1).Cells("colProjectID").Value = 1