如何从此代码中正确处理按钮? [英] How do I dispose of a button properly from this code?
本文介绍了如何从此代码中正确处理按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到的错误是:
警告26 CA2000:Microsoft.Reliability:在方法'FrmManager.LoadCategories()'中,调用System.IDisposable。在对所有引用超出范围之前对对象'btn'进行处理。
这是代码:我做错了什么?
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?
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
推荐答案
将代码包含在创建按钮的位置在使用...结束使用语句中,因为如果在循环中引发任何异常,则不会处理按钮对象...
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...
这篇关于如何从此代码中正确处理按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文