I wrote a method that deletes rows from my asp.net gridview when the delete button is pressed, and another method when the edit button is pressed. The Edit and Delete buttons are part of the gridview's built-in controls.
However, when I click these buttons (edit / delete) and an exception is thrown. Cannot pass an object of type "System.Web.UI.WebControls.GridView" to enter "System.Web.UI.WebControls.Button". that points to a string
Button btn = (Button)sender;
The problem is that this line is not associated with any of the editing or deleting methods. This is due to the asp button in another column, and for that reason I get lost. How can I solve this problem? What causes OnRowDeleting and OnRowEditing conflicts with the showResponses method?
Here is aspx
<asp:GridView runat="server" ID="gvShowQuestionnaires" HeaderStyle-CssClass="table_header" CssClass="view" AlternatingRowStyle-CssClass="alt" AlternatingRowStyle-BackColor="#f3f4f8" AutoGenerateColumns="False" DataKeyNames='QuestionnaireID' OnRowDeleting="gvShowQuestionnaires_RowDeleting" OnRowEditing="gvShowQuestionnaires_RowEdit" FooterStyle-CssClass="view_table_footer" OnRowCommand="showResponses"> <Columns> <asp:BoundField DataField="QuestionnaireID" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"></asp:BoundField> <asp:BoundField DataField="QuestionnaireName" HeaderText="Questionnaire Name" /> <asp:TemplateField HeaderText="Results" HeaderStyle-Width="150px"> <ItemTemplate> <asp:Button runat="server" ID="button1" CommandArgument='<%# Eval("QuestionnaireID") %>' OnClick="showResponses" text="Results"/> </ItemTemplate> </asp:TemplateField> <asp:CommandField HeaderText="Options" ShowDeleteButton="True" ShowEditButton="true" EditText="Edit"></asp:CommandField> </Columns> </asp:GridView>
And here is the code behind:
protected void gvShowQuestionnaires_RowDeleting(object sender, GridViewDeleteEventArgs e) { int questionnaireID = (int)gvShowQuestionnaires.DataKeys[Convert.ToInt32(e.RowIndex)].Value; GetData.DeleteQuestionnaire(questionnaireID); gvShowQuestionnaires.DataSource = DT; gvShowQuestionnaires.DataBind(); } protected void gvShowQuestionnaires_RowEdit(object sender, GridViewEditEventArgs e) { string id = gvShowQuestionnaires.Rows[e.NewEditIndex].Cells[0].Text; Session["qID"] = id; Response.Redirect("~/members/edit_questionnaire.aspx"); } protected void showResponses(object sender, EventArgs e) { Button btn = (Button)sender; string id = btn.CommandArgument.ToString(); Session["qID"] = id; Response.Redirect("~/members/questionnaire_responses.aspx"); }
Any help would be greatly appreciated.
Hgomez90
source share