Add row-specific links and commands to a Web Forms GridView
Give each GridView row a stable key and use that key for server commands. For navigation, an ordinary link is easier to inspect and works without a dynamically constructed javascript: URL.
The examples target an existing .NET Framework Web Forms page. Keep record identity separate from the visible row number, and use ordinary links that remain usable without popup scripts.
Bind keys and actions
Place this inside the server form:
<asp:GridView ID="Items" runat="server" AutoGenerateColumns="false"
DataKeyNames="Id" OnRowCommand="Items_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Open">
<ItemTemplate>
<a href='<%# "Details.aspx?id=" + Server.UrlEncode(Eval("Id").ToString()) %>'
target="_blank" rel="noopener"><%#: Eval("Name") %></a>
<asp:LinkButton ID="Inspect" runat="server" Text="Inspect"
CommandName="Inspect" CausesValidation="false"
CommandArgument='<%# ((System.Web.UI.WebControls.GridViewRow)Container).RowIndex %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="Result" runat="server" />
Add these handlers to the page class:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
Items.DataSource = new[] { new { Id = 7, Name = "Example" } };
Items.DataBind();
}
}
protected void Items_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e) {
if (e.CommandName != "Inspect") return;
var grid = (System.Web.UI.WebControls.GridView)sender;
var rowIndex = int.Parse(e.CommandArgument.ToString());
var id = (int)grid.DataKeys[rowIndex].Value;
Result.Text = "Selected ID: " + id;
}
Inspect prints Selected ID: 7. The link opens Details.aspx?id=7, which must exist in the application. Authorize access to that ID on the destination. Displaying a link is not permission enforcement.
Avoid assumptions about parent controls
In RowCommand, sender already identifies the GridView. From a child control, NamingContainer can identify its row. Prefer that semantic relationship over brittle Parent.Parent traversal. With paging, use the current row index to retrieve DataKeys. Do not confuse it with a global data-source index.
Official references


Author: Herman Schoenfeld