Question

when I try to run the below code i'm getting the error through code analysis.

//Code

For Each UltraGridRow In transactionFieldsGrid.Rows.GetAllNonGroupByRows()
      If (Field.FieldTypeId = 1000) Then
         Dim cboUltra = New UltraCombo()
         cboUltra.DataSource = LoadLookupMulticolumn(Field.LookUpCode)
         UltraGridRow.Cells("FieldValue").ValueList = cboUltra
      EndIf
 Next

//Error

CA2000 Dispose objects before losing scope In method 'TransactionFieldsController.LoadTransactionFieldsGrid(UltraGridBase, Collection(Of TransactionField), WorkflowsController, Boolean)', object 'cboUltra' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'cboUltra' before all references to it are out of scope.

To overcome this I rewritten the code as:

     For Each UltraGridRow In transactionFieldsGrid.Rows.GetAllNonGroupByRows()
          If (Field.FieldTypeId = 1000) Then
              Using cboUltra As New UltraCombo()
                cboUltra.DataSource = LoadLookupMulticolumn(Field.LookUpCode)
                UltraGridRow.Cells("FieldValue").ValueList = cboUltra
             End Using
          EndIf
     Next

But when I tried like the above code. I'm getting an Object reference error when the below line gets executed.

transactionFieldsGrid.ActiveRow = transactionFieldsGrid.Rows.GetRowAtVisibleIndex(0)

Note: The grid and rows contain values.

Any solutions?

Was it helpful?

Solution

In this case, you can't dispose the UltraCombo instances in the method because the grid has references to the UltraCombo. For disposing the UltraCombo's that you are creating, you would need to store them in a collection scoped to the form and dispose them when the form is disposed. This is necessary because within the method is too soon since the grid still needs access to the combo.

Note that if you need to use the same data for multiple drop downs in the grid, then it would be better to only have one instance of that drop down and reuse it. For this you could create a helper object that would track the instances of the UltraCombo and return the correct instance for a specific LookUpCode and if it hasn't already created the instance it would when it is requested. If these are stored in a dictionary in the helper object, you could implement IDisposable on the helper and dispose all of the UltraCombos when dispose is called on the helper. You could then have a single instance of this helper on your form and call its dispose when the form is disposed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top