Click here to Skip to main content
Rate this: bad
Please Sign up or sign in to vote.
See more: ASP.NET
Unable to cast object of type 'System.Web.UI.WebControls.Button' to type 'System.Web.UI.WebControls.GridView'.
this button is in page
protected void BtnSave_OnClick(object sender, EventArgs e)
here i want to call the bellow event method in which button is in gridview, so here i am getting error:
Unable to cast object of type 'System.Web.UI.WebControls.Button' to type 'System.Web.UI.WebControls.GridView'.
This button is in gridview
protected void btnRewrk_OnClick(object sender, EventArgs e)
   GridViewRow row = (GridViewRow)(((Control)sender).NamingContainer);
Posted 6-Dec-12 23:43pm
Tadit Dash at 7-Dec-12 6:01am
Can you please elaborate what exactly you want to do ?
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

HI anbujeremiah,
This is a link that can help you in finding your solution please have a look into it.
Access buttons in Code behind
First of all add the button to your grid as following code snippet:
                        <asp:LinkButton ID = "lnkSil" runat="server" CommandName="bla"
CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' Text= "Sil" ></asp:LinkButton>
Then add a row data bound function that can able to access the control. Follow the below code snippet.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
     int currentRowIndex = Int32.Parse(e.CommandArgument.ToString());
     LinkButton bf = (LinkButton)gv.Rows[currentRowIndex].Cells[1].Controls[0];

Thanks & Regards
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Instead of this use this
<asp:button runat="server" id="BtnSave"  rowindex="<%# Container.DisplayIndex %>" >
protected void BtnSave_OnClick(object sender, EventArgs e){
Button ibtn1 = sender as Button;
int rowIndex = Convert.ToInt32(ibtn1.Attributes["RowIndex"]);
//Use this rowIndex in your code to get which button is clicked
  GridViewRow row = Gridview.rows[rowIndex];
You dont nedd to call event of another button here.Instead you can use common method for both event.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 547
1 Member 11120668 188
2 ChauhanAjay 180
3 Maciej Los 165
4 CHill60 135
0 Sergey Alexandrovich Kryukov 9,735
1 OriginalGriff 6,987
2 CPallini 5,835
3 George Jonsson 4,017
4 Gihan Liyanage 3,266

Advertise | Privacy | Mobile
Web01 | 2.8.140926.1 | Last Updated 7 Dec 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100