这两天做CRM时用到GridView显示数据。 为了提高用户体验。想写一个单机行的事件。 结果发现GridView竟然没有这个事件 只好求助百度大神了。
最终终于找到了解决办法。好了 废话不多说了。 贴上代码
首先 在前台设置一个隐藏的ButtonField
<
Columns
>
< asp:ButtonField Visible = " False " Text = " SingleClick " CommandName = " SingleClick " />
</ 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;
}
}
{
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;
}
}
{
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);
}
{
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);
}
这样就可以运行了。 可能会出现
这时候需要在前台页面中的添加 EnableEventValidation属性。 并设置为false
<%
@ Page EnableEventValidation
=
"false
"
%>
这样基本上就没有问题了。
本文只是为了方便大家进行快速开发。 所以对其原理不甚了解。(本文作者开发时间较短) 有理解的可以给些说明。
原文地址:http://www.cnblogs.com/webabcd/archive/2007/04/22/723113.html
英文地址:http://www.codeproject.com/KB/webforms/EditGridviewCells.aspx