我在链接按钮上动态添加事件处理程序,首先在页面加载时创建带有产品类别的链接按钮。单击产品类别时,它会触发一个事件并传递product-id IN sender对象。
这是我的问题:当我在页面加载时读取事件处理程序时,它会发出错误cannot cast sender object
代码:
sub page int
Me.Page.EnableViewState = True
end sub
page load
CatDisplay()
If ViewState("GetProductClicked") = True Then
GetProduct(Me, New EventArgs)
End If
Function CatDisplay() As Boolean
Dim arr As New ArrayList
Dim objTesting As New Bo_Dall_Layer.BoCategory
arr = objTesting.GetAllCategory()
Dim objExtra As Bo_Dall_Layer.BoCategory
Dim Cat_hyperLink As LinkButton
For Each objExtra In arr
Cat_hyperLink = New LinkButton
Cat_hyperLink.Text = objExtra.CategoryName
Cat_hyperLink.CommandArgument = objExtra.CategoryId
AddHandler Cat_hyperLink.Click, AddressOf GetProduct
CatPanel.Controls.Add(New LiteralControl("<br />"))
CatPanel.Controls.Add(Cat_hyperLink)
Next
ViewState.Item("CategoryLoaded") = False.ToString
End Function
Private Sub GetProduct(ByVal sender As Object, ByVal e As EventArgs)
Dim arrCollectList As New ArrayList
Dim getLinkDetail As LinkButton = CType(sender, LinkButton)
Dim getCatID As String = getLinkDetail.CommandArgument
Dim SendCatID As Integer
SendCatID = CInt(getCatID)
Dim objGetProduct As New Bo_Dall_Layer.BoProduct
arrCollectList = objGetProduct.getSelectProduct(SendCatID)
Dim objTemCollectPrd As Bo_Dall_Layer.BoProduct
Dim lblPrdName As Label
Dim lblPrdDes As Label
Dim lblPrdPrice As Label
Dim addCart As LinkButton
For Each objTemCollectPrd In arrCollectList
lblPrdName = New Label
lblPrdDes = New Label
lblPrdPrice = New Label
addCart = New LinkButton
getCatID = objTemCollectPrd.ProductId
PrdName.Controls.Add(New LiteralControl("<br />"))
lblPrdName.Text = objTemCollectPrd.ProductName
PrdName.Controls.Add(New LiteralControl("<br />"))
PrdDesc.Controls.Add(New LiteralControl("<br />"))
lblPrdDes.Text = objTemCollectPrd.ProductDescription
PrdDesc.Controls.Add(New LiteralControl("<br />"))
lblPrdPrice.Text = objTemCollectPrd.ProductPrice
PrdPrice.Controls.Add(New LiteralControl("<br />"))
lblPrdPrice.Text = objTemCollectPrd.ProductPrice
PrdPrice.Controls.Add(New LiteralControl("<br />"))
PrdCart.Controls.Add(New LiteralControl("<br />"))
addCart.Text = "Add to Cart"
addCart.CommandArgument = objTemCollectPrd.ProductId
PrdCart.Controls.Add(New LiteralControl("<br />"))
PrdName.Controls.Add(lblPrdName)
PrdDesc.Controls.Add(lblPrdDes)
PrdPrice.Controls.Add(lblPrdPrice)
PrdCart.Controls.Add(addCart)
Next
ViewState.Item("GetProductClicked") = True
End Sub
当页面重新加载时,它给我一个错误
无法将“ASP.products_aspx”类型的对象转换为“System.Web.UI.WebControls.LinkButton”类型 Dim getLinkDetail As LinkButton = CType(sender,LinkButton)
答案 0 :(得分:2)
在行GetProduct(Me, New EventArgs)
中,您将对页面(Me)的引用作为sender参数传递。在使用此行GetProduct
的{{1}}方法中,您尝试将页面强制转换为链接按钮。您根本没有在页面加载方法中分配事件处理程序,而只是调用方法。