【问题标题】:VB.NET CheckboxList doubles when button is clicked. Why?单击按钮时,VB.NET CheckboxList 会加倍。为什么?
【发布时间】:2011-09-15 20:29:39
【问题描述】:

每次点击删除按钮,复选标记的数量都会增加一倍:

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

结束类

复选框列表未刷新,因此我删除的复选框已从复选框列表中删除。我该如何做到这一点?谢谢!

【问题讨论】:

  • 已解决:Response.Redirect("Delete.aspx")

标签: asp.net webforms


【解决方案1】:

单击按钮时,Page_Load 会再次运行,因此添加复选框的代码会再次运行。

添加对 Page.IsPostBack 的检查,如果不是回发,则仅添加复选框。

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

(我希望语法是正确的......不习惯VB)

【讨论】:

  • 谢谢!如何更新页面以删除我删除的复选框?
  • @Bruno 在 If 语句中添加 CheckBoxList1.Items.RemoveAt(count)
  • 虽然我的回答有效,但遵循 Davide Piras 的回答会更正确,因为如果未添加复选框,则不需要运行代码的第一部分。
【解决方案2】:

在您的情况下,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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 2011-01-28
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多