3.动态生成button控件,绑定事件方法

WebForm2.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <style type="text/css"></style> </head> <body> <form id="form1" runat="server"> <div> <div style="border:1px solid #808080;width:100px;height:auto;float:left;"> <asp:Table ID="HolderTable" runat="server"></asp:Table> </div>
<div style="border:1px solid #808080;width:100px;height:auto;float:left;text-align:center;"> <asp:Table ID="Tabe1" runat="server" ></asp:Table> </div> </div> </form> </body> </html>

 


WebForm2.aspx.cs
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm2 : System.Web.UI.Page
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
            CreateControl();
          CreateContro2();
        }
        string[] arr = { "深圳", "北京", "南京" };
        void CreateControl()
        {
            for (int x = 0; x < arr.Length; x++)
            {
                Table tb = new Table();
                TableRow tr = new TableRow();
                    TableCell cell = new TableCell();//格子
                   Button bt = new Button();
                    bt.Text = string.Format("{0}", arr[x]);
                    if (bt.Text == "深圳") { bt.Click += bt_Click; }
                    else if(bt.Text=="北京"){bt.Click += bt_Click2;}
                    else if(bt.Text=="南京"){bt.Click += bt_Click3;}
                   cell.Controls.Add(bt);
                  tr.Cells.Add(cell);
                  Response.Write("</div>");
                HolderTable.Rows.Add(tr);
             
               
            }
        }
        void CreateContro2()
        {
            for (int x = 0; x < arr.Length; x++)
            {
                Table tb = new Table();
                TableRow tr = new TableRow();
                TableCell cell = new TableCell();//格子
                Response.Write("<div>");
                Button bt = new Button();
                bt.Text = string.Format("{0}", arr[x]);

                if (bt.Text == "深圳") { bt.Click += bt_Click; }
                else if (bt.Text == "北京") { bt.Click += bt_Click2; }
                else if (bt.Text == "南京") { bt.Click += bt_Click3; }
                Response.Write("</div>");
                cell.Controls.Add(bt);
                tr.Cells.Add(cell);
                Tabe1.Rows.Add(tr);

            }
        }
        void bt_Click(object sender, EventArgs e)
        {
            Trace.Write("控件动态事件");
            ((Button)sender).BackColor = System.Drawing.Color.Red; 
            Ds();
         
        }
        void bt_Click2(object sender, EventArgs e)
        {
            Trace.Write("控件动态事件");
            ((Button)sender).BackColor = System.Drawing.Color.Red;      
            Ds2();

        }
        void bt_Click3(object sender, EventArgs e)
        {
            Trace.Write("控件动态事件");
            ((Button)sender).BackColor = System.Drawing.Color.Red;       
            Ds3();

        }
        void Ds()
        {
            Response.Write("你点击了该按钮");
        }
        void Ds2()
        {
            Response.Write("你点击了该按钮2");
        }
        void Ds3()
        {
            Response.Write("你点击了该按钮3");
        }
    }
}
运行效果图:单击按钮:深圳,北京,南京会执行各个方法
==========================================================================================================================================================

 完善的动态生成button

<div style="border:0px solid #ffffff; width:80px;height:120px;float:left; width:1000px;" >

                                       <div style="border:1px solid #808080;width:500px;height:20px;" ><h3>专用报表</h3>  
                                             <asp:Table ID="THolderTableZY" runat="server"></asp:Table>
                                       </div>
                                     <div style="border:1px solid #808080;width:500px;height:20px;"><h3>通用报表</h3> 
                                          <asp:Table ID="HolderTable" runat="server"></asp:Table>
                                     </div> 
                                    <div style="border:1px solid #808080;width:500px;height:20px;"><h3>主题报表</h3>  
                                        <asp:Table ID="TableZhuQi" runat="server"></asp:Table>
                                     </div>                    
                              </div>

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using CMB.MgmtCockpit.Portal.WCFService;
using CMB.MgmtCockpit.BusinessLogic;
using System.Web.Services;
using System.Web.Script.Serialization;
using CMB.MgmtCockpit.Common;

namespace CMB.MgmtCockpit.Portal._Layouts.MgmtCockpit.Portal.Report
{
    public partial class ReportingItemWithBI : PageBase
    {
        string HierarchyEName = "";

        public string SSISName
        {
            get { return ViewState["SSISName"] as string; }
            set { ViewState["SSISName"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            
            SSISName = "";
            if (this.Request.QueryString["Param"] != null)
            {
                HierarchyEName = this.Request.QueryString["Param"].ToString();
                SSISName = HierarchyEName;
            }
            if (!IsPostBack)
            {
                using (ITIL_DBEntities db = new ITIL_DBEntities())
                {
                    if (HierarchyEName != null || HierarchyEName != "")
                    {
                        BindReportData(HierarchyEName);
                    }
                    else
                    {
                        BindReportData("");
                    }
                }
            }
            if (HierarchyEName == "HRReport" || HierarchyEName == "TPReport")
            {
                BindReportData();
            } 

            CreateControl(HierarchyEName,"THolderTableZY","专用报表");//通用报表
            CreateControl(HierarchyEName, "HolderTable", "通用报表");//通用报表
            CreateControl(HierarchyEName, "TableZhuQi", "主题报表");//通用报表
           
        }


        private void BindReportData(string HierarchyEName = "")
        {
            if (HierarchyEName != "")
            {
                using (ITIL_DBEntities db = new ITIL_DBEntities())
                {
                    AspNetPager1.RecordCount = (from c in db.View_ReportingItemDetail
                                                where c.IndicatorTypeEName == HierarchyEName && c.ReportUrl != "" && c.ShowInList == 1
                                                orderby c.ReportCode
                                                select c).Count();
                    int pageIndex = AspNetPager1.CurrentPageIndex;
                    int pageSize = AspNetPager1.PageSize;
                    var ReportingItem = (from c in db.View_ReportingItemDetail
                                         where c.IndicatorTypeEName == HierarchyEName && c.ReportUrl != "" && c.ShowInList == 1 && c.ReportCode != ""
                                         orderby c.ReportCode
                                         select c).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

                    ListView_IndicatorMeaning.DataSource = ReportingItem;
                    ListView_IndicatorMeaning.DataBind();

                    var AnalysisItem = (from c in db.View_AnalysisOnLineItemDetail
                                        where c.IndicatorTypeEName == HierarchyEName && (c.PowerViewUrl != "" || c.ExcelServiceUrl != "")
                                        orderby c.ReportCode
                                        select c).ToList();


                    ListView1.DataSource = AnalysisItem;
                    ListView1.DataBind();
                }
            }
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindReportData(SSISName);
        }

        protected void ImageButton_Collection_Click(object sender, EventArgs e)
        {
            string UserID = SharepointHelper.GetUserLoginName();
            if (UserID == null || UserID == "")
            {
                Response.Redirect("../../portal/login.aspx", true);
            }
            using (ITIL_DBEntities db = new ITIL_DBEntities())
            {
                Button ib = (Button)sender;
                int RSID = int.Parse(ib.CommandArgument);
                var ReportInfo = (from c in db.View_ReportingItemDetail
                                  where c.ReportingItemDetailID == RSID
                                  select c).FirstOrDefault();

                var CollectionInfo = (from c in db.View_IndicatorPersonalCollection
                                      where c.CreateEmp == UserID && c.State == "1" && c.URL == ReportInfo.ReportUrl
                                      select c).FirstOrDefault();
                if (CollectionInfo != null && CollectionInfo.URL.Length > 0)
                {
                    this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "AddCollectione", "alert('报表已收藏,可在“我的关注”中查看。');", true);
                }
                else
                {
                    WCFService.IndicatorPersonalCollection newMeaning = new WCFService.IndicatorPersonalCollection();
                    newMeaning.CreateDate = DateTime.Now;
                    newMeaning.CollectionID = Guid.NewGuid().ToString();
                    newMeaning.CreateEmp = UserID;
                    newMeaning.Title = ReportInfo.ReportName;
                    newMeaning.CollectType = "报表浏览";
                    newMeaning.State = "1";
                    newMeaning.URL = ReportInfo.ReportUrl;
                    db.AddToIndicatorPersonalCollection(newMeaning);
                    db.SaveChanges();
                    this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "AddCollection", "alert('收藏成功,可在“我的关注”中查看。');", true);
                }
            }
        }



        //ButZhuanYong_Click  /ButZhuQi_Click"ButTY_Click
        protected void But_Click(object sender, EventArgs e)
        {
            Button a = (Button)sender; 
            BindReportData3(HierarchyEName, a.CommandArgument.ToString()); 
        } 
       
        #region 通用报表

        public void CreateControl(string reportENama,string tbname,string typename)
        {

              //<asp:Button ID="Button4" OnClick="But_Click" CommandArgument="专用报表" runat="server" Text="all专用报表"  />
            int count = 1;
            Button btone = new Button();
            btone.Text ="ALL"+ typename;

            btone.CommandArgument = typename;
            btone.Click += But_Click;

            TableRow tr = new TableRow();
            TableCell cell1 = new TableCell();//格子

            cell1.Controls.Add(btone);

            using (ITIL_DBEntities db = new ITIL_DBEntities())
            {
                var mdxList = from c in db.View_ReportingType
                              where c.IndicatorTypeEName == reportENama && c.ReportType == typename
                              group c by new { xIndicatorTypeEName = c.IndicatorTypeEName, xReportType = c.ReportType, xReportSubType = c.ReportSubType } into g
                              select new { g.Key.xIndicatorTypeEName, g.Key.xReportType, g.Key.xReportSubType };


                //组合多个结果
                MDXParam mdp = new MDXParam();
                foreach (var oneItem in mdxList)
                {
                    TableCell cell = new TableCell();//格子
                    Button bt1 = new Button();
                    bt1.Text = string.Format("{0}", oneItem.xReportSubType.ToString());

                    bt1.CommandArgument = oneItem.xReportType.ToString();
                    bt1.Click += bt_Click;
                    if (count < 2)
                    {
                        tr.Cells.Add(cell1);
                    }
                    cell.Controls.Add(bt1);
                    tr.Cells.Add(cell);
                    count++;
                }
                //HolderTable
                Table a = (Table)this.form1.FindControl(tbname);
                a.Rows.Add(tr);
            }



            //------------------------------------------------------------------------------------------------------------------------------------
          
        }
        void bt_Click(object sender, EventArgs e)
        {
            SSISName = HierarchyEName;
            Button a = (Button)sender;
            BindReportData2(HierarchyEName, a.CommandArgument.ToString(), a.Text);
        }
        #endregion

 

 



posted @ 2016-11-14 17:38  狼牙者.net  阅读(1931)  评论(0编辑  收藏  举报