Javascript – Get rowindex of gridview on click of a button outside gridview

asp.netaspxgridviewcgridviewjavascript

In my asp.net application (v4.0), I have a grid view. I use a list object to bind data to the grid view.

In the grid view there is a cancel button. On click of the cancel button the application should pop a message to the user asking for confirmation to proceed with cancel. ie. are you sure you want to cancel the record yes/no. When the user selects yes then the particular record should be cancelled.

Now the issue is, when the user selects yes then i need to the get the index of the row for which the cancel button is clicked and i need to remove it from the list object that is used to bind the grid and rebind the gridview .

please let me know how to achieve this.

Thanks for all the reply.. im using custom pop up instead of built in 'confirm' method. The custom pop up will have 'OK' and 'Cancel' button controls. Only on click of 'OK' button i need to get the selected record index. Built in confirm method mentioned in some replies will not suit my scenario. please let me know how to achieve this.

Best Answer

Add a hiddenfield into your page

<asp:HiddenField ID="HiddenField1" runat="server" />

Use the Id(use corresponding column name instead of Id) of the records as the CommandArgument of Cancel button

<asp:Button ID="btncancel" runat="server" CommandArgument='<%#Eval("Id") %>'  Text="Cancel" />

Then on clicking the cancel button it calls the gridviews rowcommand function. In that function keep the CommandArgument value in the hidden field as follows

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{

    HiddenField1.Value = e.CommandArgument.ToString();

}

Then on clicking the OK button, it calls the click event. In that function remove the Item from the List and then bind the list again to the gridview

protected void btnOK_Click(object sender, ButtonClickEventArgs e)
{
   string id = HiddenField1.Value;
   //use this id to remove the data from the List
   // bind the gridview
}