GridView/DataGrid 整行添加服务器事件

系统 1607 0

需求说明

GridView/DataGrid 本身均支持行选择事件(通过设置Button/LinkButton.CommandName="Selected",并在 SelectedIndexChanged 事件中处理)。
然而,有时候我们希望用户点击 GridView/DataGrid 一行中任意位置都可以实现触发一个事件,并在服务端对此行进行相应处理,现在我们就实现此功能。

实现方式

这里我们采取的方法有点 "hack" :
通过客户端 javascript 引发行中隐藏的按钮(Button/LinkButton 均可以)的 click 事件。

主要代码

< asp:GridView ID ="GridView1" runat ="server" AutoGenerateColumns ="false" OnRowCommand ="GridView1_RowCommand" OnRowDataBound ="GridView1_RowDataBound" >
< Columns >
< asp:TemplateField HeaderText ="ProductName" >
< ItemTemplate >
<% # Eval ( " ProductName " ) %>
< asp:Button ID ="btnHiddenPostButton" CommandName ="HiddenPostButtonCommand" runat ="server" Text ="HiddenPostButton" style ="display:none" />
</ ItemTemplate >
</ asp:TemplateField >
< asp:BoundField DataField ="UnitPrice" HeaderText ="UnitPrice" />
</ Columns >
</ asp:GridView >
protected void GridView1_RowDataBound( object sender,GridViewRowEventArgse)
{
ButtonbtnHiddenPostButton
= e.Row.FindControl( " btnHiddenPostButton " ) as Button;
if (btnHiddenPostButton != null ) {
e.Row.Attributes[
" onclick " ] = String.Format( " javascript:document.getElementById('{0}').click() " ,btnHiddenPostButton.ClientID);
// 额外样式定义
e.Row.Attributes[ " onmouseover " ] = " javascript:this.style.background='red' " ;
e.Row.Attributes[
" onmouseout " ] = " javascript:this.style.background='' " ;
e.Row.Attributes[
" style " ] = " cursor:pointer " ;
e.Row.Attributes[
" title " ] = " 单击选择当前行 " ;
}

// 若希望将隐藏按钮单独放于一列,则设置此列隐藏,占位符<cellIndex>表示此列索引
// e.Row.Cells[<cellIndex>].Attributes["style"]="display:none";
}


protected void GridView1_RowCommand( object sender,GridViewCommandEventArgse)
{
int rowIndex = - 1 ;
GridViewRowrow
= null ;
switch (e.CommandName) {
case " HiddenPostButtonCommand " : // 模板列
ControlcmdControl = e.CommandSource as Control; // 表示触发事件的IButtonControl,保持统一性并便于后续操作,我们这里直接转化为控件基类Control
row = cmdControl.NamingContainer as GridViewRow; // 当前行
// 如何访问单元格值
// stringtxt=row.Cells[0].Text;
// 如何获取模板列中的Label
// stringlbl=row.FindControl("MyLabelID")asLabel;
// 执行更多的自定义操作
//
//
Response.Write(String.Format( " GridViewVersion当前第{0}行: " ,row.RowIndex + 1 ));
break ;
// case"Command2":
// morecases
//
}

}



测试效果

GridView/DataGrid 整行添加服务器事件

GridView/DataGrid 整行添加服务器事件


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论