开发者

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.

Add a check for Page.IsPostBack, and only add the checkboxes if it is not a postback.

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)


the whole content of the Page_Load event handler has to be executed only once in your case, so rewrite it like this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜