Question Insert without Update Command

rwlopez

New member
Joined
Feb 10, 2009
Messages
3
Programming Experience
3-5
I am working on a Data Grid View and I do not want the user to be able to edit any data that has already been saved to the database. I only want them to be able to add new records. If I remove the update command for the data table them I get error message when trying to add more than one record. Does anyone have any experience with this type of scenario?
Report post as abusive
 
This should cancel the cell edit for existing rows and allow you to edit the new rows. You should be able to leave the Update statement as is.

VB.NET:
	Private Sub yourDataGridView_CellBeginEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) _
	Handles yourDataGridView.CellBeginEdit

		If Not CType(Me.yourBindingSource.Current, DataRowView).Row.RowState = DataRowState.Detached Then
			e.Cancel = True
		End If

	End Sub
 
One last step

Thank you for your response. This is what I was looking for, the only issue is that I would like to rows to to be editable until I hit the Save button which executes the .EndEdit() and .Update(Me.DataSet.MyDataTable). In other words I want to be able to enter multiple rows and be able to edit untill the records are written to the database.
 
If you're adding multiple records you'll want to check if the DataRowState is not Detached or Added and cancel those.
 
A further protection you can use is to call GetChanges(DataRowState.Added) on your datatable and save the resulting datatable instead; it will contain only the new rows

You also have the option of rejecting changes to a datarow if its state is other than added when the binding source position is changed
 

Latest posts

Back
Top