这两天做OA时用到GridView显示数据。 为了提高用户体验。想写一个单机行的事件。 结果发现GridView竟然没有这个事件 只好求助百度大神了。
最终终于找到了解决办法。好了 废话不多说了。 贴上代码
首先 在前台设置一个隐藏的ButtonField
<Columns>
<asp:ButtonField Visible="False" Text="SingleClick" CommandName="SingleClick" />
</Columns>
然后在RowDataBound和RowCommand事件里写上这些代码。
protected void gvRoleInfos_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");
e.Row.Attributes["onclick"] = _jsSingle;
}
}
protected void gvRoleInfos_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView _gridview = sender as GridView;
int _selectIndex = int.Parse(e.CommandArgument.ToString());
string _commandName = e.CommandName;
if (_commandName == "SingleClick")
{
_gridview.SelectedIndex = _selectIndex;
}
}
然后在本页面重写Render方法
protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow row in gvRoleInfos.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Page.ClientScript.RegisterForEventValidation(row.UniqueID + "$ct100");
Page.ClientScript.RegisterForEventValidation(row.UniqueID + "$ct101");
Page.ClientScript.RegisterForEventValidation(row.UniqueID + "$ct102");
}
}
base.Render(writer);
}
原文地址:http://www.cnblogs.com/webabcd/archive/2007/04/22/723113.html
英文地址:http://www.codeproject.com/KB/webforms/EditGridviewCells.aspx