In the previous study essay, we can use DataKeyNames and DataKeys to perform data access on the GridView primary key column. In subsequent experiments, I found that we can use TemplateField to achieve other data access.
<asp:TemplateField Visible="False">
<ItemTemplate>
<asp:Literal id="litUserName" runat="Server" Text='<%#Eval("UserName")%>'/>
</ItemTemplate>
</asp:TemplateField>
//Backend implementation
String userName = ((Literal)GridView1.SelectedRow.FindControl("litUserName")).Text;
The AutoGenerateSelectButton property of GridView can directly enable table selection. If we do not want to add an extra column for selection, we can use TemplateField to implement GridView selection.
The ASP.NET code is as follows:
<asp:BoundField DataField="ObjectID" HeaderText="ID"/>
<asp:TemplateField>
<HeaderTemplate>
Name
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton id="lbName" runat="Server" CommandName="Select">
<%#Eval("Name")%>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Status" HeaderText="Status"/>
At the same time, we need to add two event handlers to GridView: RowCreated and RowCommand.
//RowCreated event handling
void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{ ((LinkButton)e.Row.FindControl("lbName")).CommandArgument = e.Row.RowIndex.ToString();
}
}
//RowCommand event handling
void GridView1_RowCommand(object source, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
GridView1.SelectedIndex = int.Parse(e.CommandArgument.ToString());
}
In this way, you can select at the same time when you click on the name, without having to use the selection column.