Error : "Operation cannot be performed in this event handler" while setting value to grid view
I am trying to add values from Arraylist to particular column of grid view. as :
If (Arr_NewContacts.Count > 0) Then
dgvStayout.Rows.Clear() ' **GETTING ERROR HERE**
dgvStayout.Rows.Insert(0, (Arr_NewContacts.Count - 1))
For i As Integer = 0 To Arr_NewContacts.Count - 1
dgvStayout开发者_开发百科.Rows(i).Cells("Name").Value = Arr_NewContacts(i).ToString
dgvStayout.Rows(i).Cells("CheckIn Date").Value = Date.Today
dgvStayout.Rows(i).Cells("CheckOut Date").Value = Date.Today
IsStayGrid_added = True
Next
End If
Datagrid property like AllowUserToAddRows and AllowUserToDeleteRows is already set to true :
I am using above code on lost focus event of one of text box.
Thanks
I ran into a similar issue this morning and tracked down the cause of this exception. I took a look at the DataGridView source and found that in the Columns and Rows clear methods the code is checking an internal property called NoDimensionChangeAllowed. If this is false then the InvalidOperationException is thrown with the "Operation cannot be performed in this event handler" message.
I found there eight DataGridView event handlers in which this property is affected and you cannot modify the number of rows or columns:
CellEnter
CellLeave
CellValidated
CellValidating
RowEnter
RowLeave
RowValidated
RowValidating
Therefore you need to ensure that this block of code is not being run inside any of these handlers. If you must run the code as a result of one of these events then you need to run it via a BeginInvoke as suggested here: Failure to validate, but cannot remove in DataGridView
Had similar issue, trying to add a row to a datagridview based on user input for a cell in current row (a linked item for a shipment): had to put code for adding new row in a Sub (AddExtraShipLines), then use this syntax inside the event handler (CellEndEdit):
BeginInvoke(New Action(AddressOf AddExtraShipLines))
精彩评论