如题:我想根据用户的需求,在页面中动态的添加控件DropDownList,并且为DropDownList添加事件。如何能办得到?

解决方案 »

  1.   

    重写下面事件protected override void OnInit(EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("id"));
            dt.Columns.Add(new DataColumn("MenuName"));
            dt.Columns.Add(new DataColumn("ParentID"));
            dt.Rows.Add(new object[] { "1", "电器", "0" });
            dt.Rows.Add(new object[] { "2", "家具", "0" });
            dt.Rows.Add(new object[] { "3", "电器", "1" });
            DropDownList ddl = new DropDownList();
            ddl.DataSource = dt;
            ddl.DataTextField = "MenuName";
            ddl.DataValueField = "id";
            ddl.DataBind();
            ddl.AutoPostBack = true;
            ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
            Panel1.Controls.Add(ddl);
            base.OnInit(e);
        }
      

  2.   


    void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
           Response.Write(((DropDownList)sender).SelectedValue);
     }
      

  3.   

    DropDownList _DropDownList = new DropDownList();
    _DropDownList.SelectedIndexChanged+=YouEventHandle;
    _Panel.Controls.Add(_DropDownList);
      

  4.   

    用jquery 动态前台增加行不呢?
      

  5.   


    我的目的是循环增加控件,并添加该控件的事件,你看怎么写比较。重写的 OnInit(EventArgs e) ,它是在页面初始化的时候执行……
      

  6.   

    javascript的写法是
    mydropdownlist = document.createElement("<select id='mydropdownlist' />");
    mydropdownlist.attachEvent("onchange", myfunction);
    当然,如果要绑定数据,还得用服务器控件,用c#写
      

  7.   


     protected void Page_Load(object sender, EventArgs e)
            {
                if (ViewState["isok"] != null)
                {
                    CreateDropDownList();
                }
            }
            protected void Button1_Click(object sender, EventArgs e)
            {
                CreateDropDownList();
            }        private void CreateDropDownList()
            {
                DropDownList list = new DropDownList();
                list.ID = "DropDownList1";
                list.AutoPostBack = true;
                ListItem item = null;
                for (int i = 0; i < 5; i++)
                {
                    item = new ListItem();
                    item.Text = i.ToString();
                    item.Value = i.ToString();
                    list.Items.Add(item);
                }
                list.SelectedIndex = 0;
                list.SelectedIndexChanged += new EventHandler(list_SelectedIndexChanged);
                this.form1.Controls.Add(list);
                ViewState["isok"] = "true";
            }        void list_SelectedIndexChanged(object sender, EventArgs e)
            {
                Response.Write((sender as DropDownList).SelectedItem.Text);
            }
      

  8.   

    1. 把DropDownList 隐藏起来 visible=false
    2. 需要的时候 动态绑定数据源  把DropDownList 显示出来
      

  9.   


    可是DropDownList 数量不固定啊,如果固定,那么我就不用动态的了