当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET Web控件按钮事件加载无效

ASP.NET Web控件按钮事件加载无效

2018年11月04日  | 移动技术网IT编程  | 我要评论

很久不做asp.net 了,工作需要又捡起来,做一个toolbar,动态添加操作按钮。

   /// <summary>
        /// 初始化构造
        /// </summary> 
        public tktoolbar()
        {
            btnexprot = new button();
            btnexprot.commandname = btn_export;          
            btnexprot.cssclass = "btn_dc";
                  

             btnexprot.click += new eventhandler(btn_click);
             }

  /// 统一处理按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btn_click(object sender, eventargs e)
        {
            button btn = sender as button;

 if (btn.commandname == btn_export)
            {
                if (onexportclick != null)
                {
                    onexportclick(sender, e);
                }
            }

  }

  /// <summary>
        /// 控件呈现
        /// </summary>
        /// <param name="writer"></param>
        protected override void render(htmltextwriter writer)
        {
            writer.write("<table width=\"" + this.width + "\" border=\"0\" cellspace=\"0\" cellpadding=\"0\"><tr><td align=\"right\">");
           //导出按钮
            if (!string.isnullorempty(buttonexportscript))
            {
                btnexprot.onclientclick = buttonexportscript;
            }

        if (buttonexport && (!rightctrl||(rightctrl && permissionright.exportenable)))
            {
                btnexprot.rendercontrol(writer);
            }

  }

上面代码执行时显示均正常,但是就是服务器端按钮事件无效,郁闷。

折腾了半天,原来是没有将按钮控件添加到控件集合中,

缺少 this.controls.add(btnexprot);这一句。

修改

/// <summary>
        /// 初始化构造
        /// </summary> 
        public tktoolbar()
        {
            btnexprot = new button();
            btnexprot.commandname = btn_export;          
            btnexprot.cssclass = "btn_dc";
                  
             btnexprot.click += new eventhandler(btn_click);

          this.controls.add(btnexprot);
             }

就可以了,原因是,虽然呈现了按钮,但是由于控件树没有构建相互关系,按钮的事件无法进行向上冒泡。

属于低级失误,记于此

 


摘自 ysh的专栏

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网