GridView中利用隐藏的TemplateFied来进行数据访问_[Asp.Net教程] 在上一个学习随笔中我们可以利用DataKeyNames和DataKeys来进行GridView主键列的数据访问, 在后来试验中,我发现我们可以利用TemplateField来实现其他的数据访问.
//后台实现
String userName = ((Literal)GridView1.SelectedRow.FindControl("litUserName")).Text;
GridView的AutoGenerateSelectButton属性可以直接使表格实现选择, 如果不想多增加一列选择列, 我们可以利用TemplateField实现GridView的选择.
ASP.NET代码如下:
Name
<%#Eval("Name")%>
同时要给GridView增加两个事件处理RowCreated, RowCommand
//RowCreated事件处理
void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{ ((LinkButton)e.Row.FindControl("lbName")).CommandArgument = e.Row.RowIndex.ToString();
}
}
//RowCommand事件处理
void GridView1_RowCommand(object source, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
GridView1.SelectedIndex = int.Parse(e.CommandArgument.ToString());
}
这样在点击名称时就可以同时进行选择,不必再利用选择列.
来源:网络