当前位置:编程学习 > asp >>

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

很久不做ASP.NET 了,工作需要又捡起来,做一个易做图,动态添加操作按钮。

   /// <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的专栏

补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,