You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.Net动态生成的删除按钮无法触发DeleteButton_Click函数

问题原因

ASP.NET WebForms中,动态生成的服务器控件必须在每次页面回发时重新创建并加入控件树,否则ASP.NET无法找到对应的控件实例,绑定的事件自然无法触发。你当前仅在IsPostBack = False时调用BindCartItems(),点击删除按钮触发回发时,动态按钮不会被重建,导致DeleteButton_Click函数无法执行。

解决方案

1. 修改Page_Load方法,确保每次加载都重建动态控件

移除IsPostBack判断,让BindCartItems()在每次页面加载(包括回发)时都执行,保证动态按钮能被重新创建:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     MAXORDER_id = Server.UrlDecode(Request.QueryString("var"))
     ' 每次加载都绑定购物车项,重建动态控件
     BindCartItems()
     CalculateTotalBill()
End Sub

2. 额外优化建议

  • 确保cartItems是带runat="server"属性的服务器端容器(比如Panel),否则无法添加动态服务器控件。
  • 可将MAXORDER_id存入Session,避免依赖QueryString(回发时QueryString可能因场景丢失):
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
         If Not IsPostBack Then
             MAXORDER_id = Server.UrlDecode(Request.QueryString("var"))
             Session("MAXORDER_id") = MAXORDER_id
         Else
             MAXORDER_id = Convert.ToInt32(Session("MAXORDER_id"))
         End If
         BindCartItems()
         CalculateTotalBill()
    End Sub
    
  • 动态控件ID需保持稳定:你当前用rowIdCounter生成cartRow_0、cartRow_1这类ID,每次绑定从0开始计数的逻辑是正确的,能保证回发时控件ID一致,ASP.NET可正确关联ViewState与事件。
修改后的关键代码示例
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     If Not IsPostBack Then
         MAXORDER_id = Server.UrlDecode(Request.QueryString("var"))
         Session("MAXORDER_id") = MAXORDER_id
     Else
         MAXORDER_id = Convert.ToInt32(Session("MAXORDER_id"))
     End If
     BindCartItems()
     CalculateTotalBill()
End Sub

Protected Sub BindCartItems()
    Dim loggedInCustomerId As Integer = Convert.ToInt32(Session("LoggedInCustomerID"))
    Dim rowIdCounter As Integer = 0

    Using connection As New SqlConnection(connectionString)
        Dim query As String = "SELECT ol.Product_Id, p.Product_Name, p.Product_Price, p.ImageURL, ol.quantity " &
                              "FROM Order_Line ol INNER JOIN Product p ON ol.Product_Id = p.Product_Id " &
                              "WHERE ol.order_id IN (SELECT order_id FROM orderTable WHERE customer_id = @customerId)"
        Dim command As New SqlCommand(query, connection)
        command.Parameters.AddWithValue("@customerId", loggedInCustomerId)

        connection.Open()
        cartItems.Controls.Clear()

        Using reader As SqlDataReader = command.ExecuteReader()
            While reader.Read()
                Dim productId As Integer = Convert.ToInt32(reader("Product_Id"))
                Dim productName As String = reader("Product_Name").ToString()
                Dim productPrice As Decimal = Convert.ToDecimal(reader("Product_Price"))
                Dim imageURL As String = reader("ImageURL").ToString()
                Dim quantity As Integer = Convert.ToInt32(reader("quantity"))

                Dim cartRow As New HtmlGenericControl("div")
                cartRow.Attributes("class") = "cart-row"
                cartRow.ID = "cartRow_" & rowIdCounter
                rowIdCounter += 1

                Dim productImage As New Image()
                productImage.Attributes("class") = "product-image"
                productImage.ImageUrl = imageURL
                productImage.Width = 50
                productImage.Height = 70

                Dim productDetails As New HtmlGenericControl("div")
                productDetails.Attributes("class") = "product-details"
                productDetails.Style("display") = "flex"
                productDetails.Style("align-items") = "center"
                productDetails.Style("gap") = "50px"

                productDetails.InnerHtml = $"<div class='product-name'>{productName}</div>" &
                      $"<div>Price: ${productPrice}</div>" &
                      $"<div>Quantity: {quantity}</div>" &
                      $"<div>Total: ${productPrice * quantity}</div>"

                Dim deleteButton As New Button()
                deleteButton.Attributes("class") = "delete-button"
                deleteButton.Text = "Delete"
                deleteButton.CommandArgument = productId.ToString()
                AddHandler deleteButton.Click, AddressOf DeleteButton_Click

                productDetails.Controls.Add(deleteButton)
                cartRow.Controls.Add(productImage)
                cartRow.Controls.Add(productDetails)

                cartItems.Controls.Add(cartRow)
            End While
        End Using
    End Using
End Sub

内容的提问来源于stack exchange,提问作者Abdullah Alamgir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 18:35:18