0

I get it. Datagridview cannot be in the process of changing ANYTHING. I don't think I am, yet I still occasionally get this exception. That's what is so odd. More than 90+% of the time it works just fine.

I have a tabcontrol on a windows form and multiple of the tabpages have datagrid view controls. None of them are bound to the database. As the user navigates through the tab pages, there is code for each tabpage 'enter' and 'leave' event. Upon entry to the tabpage, if there is a DGV control, there is a line of code to clear all rows.

Private Sub Tab3_Plan_Enter(ByVal sender As Object, ByVal e As System.EventArgs) _
    Handles Tab3_Plan.Enter

        dgPlan.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
        CircuitItems = LoadCatalogItems(dgPlan, cbVDSvcLocation, iKind.PlanSku)
        ' More event code

Private Function LoadCatalogItems(ByRef DGV As DataGridView, _
                    ByVal cbControl As System.Windows.Forms.ComboBox, _
                    ByRef ItemKind As Integer) As Integer
        Dim DescDGName As String
        Dim OrigInternalDesc As String
        Dim DisplayDesc As String

        DGV.Rows.Clear()   ' <-- This is where the exception is thrown
        ' More function code

Could the AutoSizeRowMode in the Tab3_Plan_Enter event handler have anything to do with this? If so, how can I overcome it? Would reordering the two lines of code in Tab3_Plan_Enter be a good idea?

Community
  • 1
  • 1
Ebassador
  • 339
  • 3
  • 20

1 Answers1

1

This exception is raised when you try to do something with a cell that is currently being used.

Try adding a Thread.Sleep(5000) after DGV.Rows.Clear() to give it some time to clear the DataGridView. Since you said it happens only sometimes, it may be that the DataGridView has too many rows and it takes a while to clear everything. Since you're probably adding more rows afterwards, this is a feasible scenario.

If it works you may lower the amount of seconds to sleep in order to halt the thread only as long as needed.

Diego Bauleo
  • 681
  • 3
  • 12
  • I think you meant before the DGV.Rows.Clear. I'm giving it a try. It could take awhile before I know if this fixes the problem. – Ebassador Oct 19 '15 at 23:24