防止项目多次加载(For 循环查看数据库并为数据库中的每个项目创建按钮)

Prevent items from loading more than once (For loop looks at database and creates button for each item in database)

我有以下过程为我的数据库中的每个项目创建一个按钮:

Public Sub AddButtons()

            'Procedure creates a button for each category
        'stored in the database and adds them to the
        'main panel

        Dim ta As New ContactsAndInventoryDataSetTableAdapters.PRODUCT_CATEGORYTableAdapter
        Dim dt As DataTable = ta.GetData


        For Each row As DataRow In dt.Rows

            Dim btn As New btnCategoryTabs()

            btn.lblCategoryName.Name = DirectCast(row("Category_Name"), String)
            btn.lblCategoryName.Text = btn.lblCategoryName.Name
            btn.lblCategoryID.Text = CStr(row("Category_ID"))

            Using STREAM As New MemoryStream(DirectCast(row("image"), Byte()))
                btn.picPCategoryPicture.Image = Image.FromStream(STREAM)
            End Using

            'Add categories to the Panel
            frmManageStore.flpMainPanel.Controls.Add(btn)

        Next

End Sub

效果很好,但是,每次用户单击按钮时,我的面板都会复制我的项目,因为程序 运行s 再次出现。为了防止我写了以下内容:

    Public Sub removeButtons()

    'This procedure is used to remove buttons from the panel
    'after each category is clicked--

       Dim btnList As List(Of btnCategoryTabs) = frmManageStore.flpMainPanel.Controls.OfType(Of btnCategoryTabs).ToList()

    'Remove these Buttons
    For Each btn As btnCategoryTabs In btnList

        btn.Dispose()

    Next

End Sub

我的点击按钮事件如下:

    Private Sub btnCategories_Click(sender As Object, e As EventArgs) Handles btnCategories.Click

    PublicSubs.removeButtons()
    PublicSubs.addCategories()

End Sub

一些用户建议不要使用 .Dispose 所以我的问题是,如果用户多次单击按钮,是否有更好的方法来防止我的项目重复。下图显示了当用户多次单击类别按钮并且 PublicSubs.removeButtons() 没有 运行.

时发生的情况

只需调用 frmManageStore.flpMainPanel.Controls.Clear() 即可从面板中删除所有按钮。

请注意 btn.Dispose() 确实从 Controls 集合中删除了按钮;然而,这并不明显,可以认为是 Dispose 方法的 side effect。因此,最好明确删除按钮。这让你的意图更明确。

Public Sub AddButtons() 之后添加:

frmManageStore.flpMainPanel.Controls.Clear()

这将在添加新控件之前清除现有控件,从而消除重复项。