<
asp:TemplateField
Visible
="False"
>
< ItemTemplate >
< asp:Literal id ="litUserName" runat ="Server" Text ='<%#Eval("UserName")% > '/>
</ ItemTemplate >
</ asp:TemplateField >
//后台实现
String userName = ((Literal)GridView1.SelectedRow.FindControl("litUserName")).Text;
< ItemTemplate >
< asp:Literal id ="litUserName" runat ="Server" Text ='<%#Eval("UserName")% > '/>
</ ItemTemplate >
</ asp:TemplateField >
//后台实现
String userName = ((Literal)GridView1.SelectedRow.FindControl("litUserName")).Text;
GridView的AutoGenerateSelectButton属性可以直接使表格实现选择, 如果不想多增加一列选择列, 我们可以利用TemplateField实现GridView的选择.
ASP.NET代码如下:
< 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" />
同时要给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());
}
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());
}
这样在点击名称时就可以同时进行选择,不必再利用选择列.