Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The error I am getting is this:

Warning 26 CA2000 : Microsoft.Reliability : In method 'FrmManager.LoadCategories()', call System.IDisposable.Dispose on object 'btn' before all references to it are out of scope.

Here is the code: What am I doing wrong please?

VB
Public Sub LoadCategories()
        Try
            If cn.State = ConnectionState.Closed Then
                cn.Open()
            End If

            Dim sql As String = "Select Category from Categories ORDER BY Category Asc"

            Using ds As New DataSet
                Using da As New OleDb.OleDbDataAdapter(sql, cn)
                da.Fill(ds)
                End Using

                If ds.Tables(0).Rows.Count = 0 Then
                    MsgBox("No categories were found.", MsgBoxStyle.Critical, "NO RECORDS!")
                    Exit Sub
                End If

                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    Dim btn As New Button
                    Try

                        AddHandler btn.Click, AddressOf CategoryLoadClick
                        btn.Width = 75
                        btn.Height = 50
                        btn.Text = ds.Tables(0).Rows(i)("Category").ToString
                    Catch ex As Exception
                        If Not btn Is Nothing Then
                            btn.Dispose()
                        End If
                        MsgBox(ex.Message)
                    End Try

                Next
             
                flowlayoutpanel.Controls.Add(btn)
            End Using
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            cn.Close()
        End Try
Posted
Updated 16-Aug-15 12:15pm
v2
Comments
PIEBALDconsult 9-Aug-15 13:46pm    
Remove it from the Controls collection of its parent?
You can try simply setting Visible to false instead.
FMWorx LLC 9-Aug-15 22:56pm    
How does hiding it, dispose it?
PIEBALDconsult 9-Aug-15 23:19pm    
It doesn't. I'm saying you may not need to dispose it. Are you sure you really do?
FMWorx LLC 16-Aug-15 18:18pm    
Code Analyser is giving me error for not disposing buttons
PIEBALDconsult 16-Aug-15 20:29pm    
Then don't use it.

1 solution

Enclose the code where you create buttons within "Using...End Using" statements because if any exception is raised in you for loop the button object will not be disposed...
 
Share this answer
 
v2
Comments
FMWorx LLC 16-Aug-15 18:17pm    
I have tried to add the using...end using, but then the buttons disappear of the flow layout panel.....

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900