这个帖子推荐了,不过很多人不理解推荐的原因。
现 写一可运行版本,并简要说明推荐的理由。
WebForm中一个重要特点就是事件机制,如果只会拖拽控件而不了解事件机制的话,那只会流于表面。
WebForm中有个回发的概念,意思就是当前页面进行post提交action指向的是本页。
IPostBackEventHandler 这个接口是实现回发的一个重要手段,回发后会触发 RaisePostBackEvent 这个方法。
如果我们希望回发后做些什么的话,那就可以在 RaisePostBackEvent 方法中来写,假如希望由外部来指定具体操作的话,那可以通过委托的方式来给外部提供扩展。
本文主要就是使用了以上几种手段,之前的帖子也是,
这里面要理解 ASP.NET Page Life Cycle 之后,才会更清晰的明白相关代码的运转流程,才能真正弄清楚为何要这么写。不要总有黑盒子来阻碍你对知识的掌握。
程序的思路就是在行被双击时,触发页面的 js 代码,就是一 js 函数,
假定是函数TableDblClick,函数内要做的事就是让页面回发,同时把当前被双击行的信息传递回去。
然后 RaisePostBackEvent 方法来接收相关参数,并触发相关的事件,进而调用外部所定义的方法。
代码如下:
public delegate void RowDblClickEventHandler(object sender, int RowIndex);
[ParseChildren(true)] [PersistChildren(false)] [ToolboxData("<{0}:GridViewPlus runat=server></{0}:GridViewPlus>")] [ToolboxBitmap(typeof(GridView))] public class CustomGridView : GridView, IPostBackEventHandler { private const string JS= @" var TableDblClick = function (evt) {0} evt = evt.target || event.srcElement; if (evt.tagName == 'TD' && evt.parentNode.tagName == 'TR') {0} var index=evt.parentNode.rowIndex - 1; {2}; {1} {1}"; public event RowDblClickEventHandler RowDblClick; protected virtual void OnRowDblClick(object sender, int RowIndex) { if (RowDblClick != null) { RowDblClick(sender, RowIndex); } } protected override void Render(HtmlTextWriter writer) { //为GridView生成的table 添加ondblclick this.Attributes.Add("ondblclick", "TableDblClick(event);"); //组装js函数 string fn = string.Format(JS, "{", "}", Page.ClientScript.GetPostBackEventReference(this, "").Replace("''", "index")); //输出到页面 Page.ClientScript.RegisterStartupScript(typeof(CustomGridView), "DblClick", fn, true); base.Render(writer); } void IPostBackEventHandler.RaisePostBackEvent(string eventArgument) { int index; int.TryParse(eventArgument, out index); //触发事件 OnRowDblClick(this, index); } }//endclass
调用代码:
<%@ Register TagPrefix="WebApp1" Namespace="WebApplication1" Assembly = "WebApplication1" %>
这里因为之前的 Namespace 是 WebApplication1,需要改成对应的 Namespace ,Assembly 也是一样。
页面标记
<WebApp1:CustomGridView ID="cgv" runat="server" onrowdblclick="cgv_RowDblClick"> </WebApp1:CustomGridView>
相关事件
protected void cgv_RowDblClick(object sender, int RowIndex) { ClientScript.RegisterClientScriptBlock(GetType(), "alert", "alert(" + RowIndex.ToString() + ")", true); }
GridVIew 这种重量级控件在实际开发中用的非常少,这里只是用它来演示相关技术的实现。