<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;
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());
}
这样在点击名称时就可以同时进行选择,不必再利用选择列.
新闻热点
疑难解答