简体   繁体   English

单击按钮时,VB.NET CheckboxList会加倍。 为什么?

[英]VB.NET CheckboxList doubles when button is clicked. Why?

Every time I click the Delete Button, the check marks double in quantity: 每次单击“删除”按钮时,复选标记的数量都会翻倍:

Public Class About
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim di As New IO.DirectoryInfo("C:\Images\")
    Dim imageArray As IO.FileInfo() = di.GetFiles()
    Dim image As IO.FileInfo

    'clear imageArray


    'list the names of all images in the specified directory
    For Each image In imageArray
        CheckBoxList1.Items.Add(image.Name)
    Next

End Sub

Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDelete.Click

    For count As Integer = 0 To CheckBoxList1.Items.Count - 1
        If CheckBoxList1.Items(count).Selected Then
            File.Delete("C:\Images\" & CheckBoxList1.Items(count).ToString)
        End If
    Next

End Sub

End Class 末级

The checkboxlist isn't refreshed so that the checkbox that I deleted is removed from the checkboxlist. 该复选框列表未刷新,因此我删除的复选框从该复选框列表中删除。 How do I accomplish that? 我该怎么做? Thanks! 谢谢!

On a button click, Page_Load is ran again, so the code that adds the checkboxes is ran a second time. 单击按钮后,将再次运行Page_Load,因此将再次运行添加复选框的代码。

Add a check for Page.IsPostBack, and only add the checkboxes if it is not a postback. 添加对Page.IsPostBack的检查,并且如果不是回发,则仅添加复选框。

If Not Page.IsPostBack Then
    For Each image In imageArray
        CheckBoxList1.Items.Add(image.Name)
    Next
End If

(I hope syntax is right... Not used to VB) (我希望语法是正确的...不习惯VB)

the whole content of the Page_Load event handler has to be executed only once in your case, so rewrite it like this: Page_Load事件处理程序的全部内容在您的情况下仅需执行一次,因此应将其重写为:

If Not IsPostBack Then

    Dim di As New IO.DirectoryInfo("C:\Images\")
    Dim imageArray As IO.FileInfo() = di.GetFiles()
    Dim image As IO.FileInfo

    'clear imageArray


    'list the names of all images in the specified directory
    For Each image In imageArray
        CheckBoxList1.Items.Add(image.Name)
    Next

End If

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM