在浏览器中查看时,我收到此错误: 无法将“ASP.webform1_aspx”类型的对象强制转换为“System.Web.UI.WebControls.Button”。
我该如何解决这个问题?
Line 7: If Not Page.IsPostBack Then
Line 8: Dim rowIndex As Integer = 0
<b>Line 9: Dim btn As Button = DirectCast(sender, Button)</b>
Line 10: 'Get reference of the gridview row of the button clicked.
Line 11: Dim GridView2 As GridViewRow = DirectCast(btn.Parent.Parent, GridViewRow)
Line 12: Dim txt1 As TextBox = TryCast(GridView2.Cells(1).FindControl("TextBox1"), TextBox)
答案 0 :(得分:1)
您正在使用错误的对象。您的sender
是您的网络表单,或btn.Parent.Parent
是您的网络表单。显然,您无法将Web表单转换为按钮。
如果此代码包含在Button_Click
事件中,那么您的发件人可能是一个按钮。在这种情况下,我会将btn.Parent.Parent
更改为btn.Parent
,因为如果下一级是网络表单,那可能是您的网格视图行。
更新:看起来这是Page_Load
事件。在这种情况下,sender
是Web表单而不是按钮。请直接参阅按钮名称以解决问题。
答案 1 :(得分:0)
您正在页面加载事件中修改此代码,在这种情况下,发件人对象是页面本身,并且您正在尝试将该发件人强制转换为按钮控件。我认为这个事件不是因为一个按钮而被解雇,而是因为一个页面。
删除此行并且问题消失
<b>Line 9: Dim btn As Button = DirectCast(sender, Button)</b>