When you need to pull data from a GridView, e.g. when the user selects the row and you want to populate
some fields that match data from the selected row, it is pretty common to simply reference the cell
that was clicked on. If you used a normal databound column, you could call the Text property of the cell.
' Select the row somehow (multiple ways depending on what you're doing)
TextBox1.Text = row.Cells[1].Text
If you used a TemplateField, you can simply look for the ID of the control containing the value, cast it,
and extract the value.
' Select the row somehow (multiple ways depending on what you're doing)
TextBox1.Text = CType(row.FindControl("litHolderType"), Literal).Text
If you are looking for the primary key(s) for the given row, the best way to do it is to first set
the DataKeyNames property on the GridView, then reference it in the code-behind.
Populate the key(s) as follows:
<asp:GridView ID="gvHolders" runat="server" DataKeyNames="Emplid,TypeID" .... >
Reference the datakeys in code-behind as follows (e.g. RowEditing event in this example):
Dim iEmplid As String = gvHolders.DataKeys(e.NewEditIndex).Values("ID")
Dim iTypeID As Integer = gvHolders.DataKeys(e.NewEditIndex).Values("TypeID")
Alternate Option
You can bypass the built-in GridView edit/select functionality by adding a button with manually-specified parameters that trigger a custom function in the code-behind, with a variable passed through as a CommandArgument
.
GridView Column:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnDoSomething" runat="server" CommandName="DoSomething"
CommandArgument="<%#Eval('id')%>" OnCommand="DoSomething" CssClass="item-edit"
ToolTip="Edit Holder" data-toggle="tooltip" data-placement="right">
<i class="fa fa-pencil-square-o" aria-hidden="true"></i>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Code-Behind Function:
Protected Sub DoSomething(Sender As Object, e As CommandEventArgs)
' Access command name through e.CommandName
' Access command argument through e.CommandArgument
End Sub