Reputation: 45
when view in browser, i got this error: Unable to cast object of type 'ASP.webform1_aspx' to type 'System.Web.UI.WebControls.Button'.
how should i solve this problem?
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)
Upvotes: 0
Views: 1830
Reputation: 13820
You are working with the wrong object. Either your sender
is your web form or btn.Parent.Parent
is your web form. Obviously, you can't cast a web form as a button.
If this code is contained in a Button_Click
event, then your sender is probably a button. In that case, I would change btn.Parent.Parent
to btn.Parent
because that is probably your grid view row if the next level up is the web form.
UPDATE: It looks like this is in the Page_Load
event. In that case, the sender
is the web form and not the button. Refer to the button name directly to fix the issue.
Upvotes: 1
Reputation: 2689
You're righting this code inside the page load event in which case the sender object is the page itself and you're trying to cast that sender to a button control. The event I think is not fired because of a button but rather because of a page.
Remove this line and problem is gone
<b>Line 9: Dim btn As Button = DirectCast(sender, Button)</b>
Upvotes: 0