【精华】如何让动态加载的ascx里2个DroDdownList联动起来?100分+如题目。
1.aspx里用
Control c = Page.LoadControl("Control/A.ascx");
this.main.Controls.Add(c);
加载用户自定控件。
如何让A.ascx里2个DroDdownList联动起来?

解决方案 »

  1.   

    经测试,下面这样OK:
    public class WebUserControl1 : System.Web.UI.UserControl
    {
    protected System.Web.UI.WebControls.DropDownList dd1;
    protected System.Web.UI.WebControls.DropDownList dd2; private void Page_Load(object sender, System.EventArgs e)
    {
                 dd1.AutoPostBack = true;
    }
    override protected void OnInit(EventArgs e)
    {
    InitializeComponent();
    base.OnInit(e);
    }
    private void InitializeComponent()
    {
    this.dd1.SelectedIndexChanged += new System.EventHandler(this.dd1_SelectedIndexChanged);
    this.Load += new System.EventHandler(this.Page_Load);
    }
    private void dd1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
    Response.Write("<script>alert('1')<script>;");//这里改写成绑定dd2
    }
    }
    然后使用Control c = Page.LoadControl("WebUserControl1 ");
    this.main.Controls.Add(c); 测试时main是在form中的panel
      

  2.   

    举个例子吧,在控件里写就是了,和页面没有任何关系的。
    private void DrplstCityBind()
    {
    int provinceID=Convert.ToInt32(drplstProvince.SelectedItem.Value);
    drplstCity.DataSource=City.ListCity(provinceID);
    drplstCity.DataTextField="Name";
    drplstCity.DataValueField="ID";
    drplstCity.DataBind();
    drplstCity.Items.Insert(0,new ListItem("-- Select --","0"));
    }
    private void drplstProvince_SelectedIndexChanged(object sender, System.EventArgs e)
    {
    DrplstCityBind();
    }
    记得把第一个dropdownlist(在本例中是drplstProvince)的AutoPostBack属性设为1
      

  3.   

    erwanfan(teddyxiong) 
    我用的是VS2005 
    自定义控件是按钮选着添加的。
    你的方法会让页面刷新为初试状态,就没有B.ascx控件了。
      

  4.   

    1.aspx的初试状态是没加载控件的。
    点击按钮后用
    Control c = Page.LoadControl("WebUserControl1 ");
    this.main.Controls.Add(c);
    的方法 加载用户自定义控件。
    然后在使用 用户自定义控件 里的 dropdownlist。
      

  5.   

    dd1.AutoPostBack = true;
    只要开启AutoPostBack属性就会刷新页面 就会回到没加载控件时的状态。
      

  6.   

    把Control c = Page.LoadControl("WebUserControl1 ");
    this.main.Controls.Add(c);
    放到if(!IsPostBack){}之外,每次post就加载一边就行了。
      

  7.   

    我就是放那外面的呀。不行呀。能不能QQ?让你QQ看
      

  8.   

    1.aspx
     <form>
    <div>
    <asp:LinkButton ID="h07" runat="server"OnClick="h07_Click">A</asp:LinkButton>
    </div>
            <div >
                <asp:PlaceHolder ID="main" runat="server"></asp:PlaceHolder>
            </div>
     </div>
    </form>
    1.cs
        protected void h07_Click(object sender, EventArgs e)
        {
            this.main.Dispose();
            Control c = Page.LoadControl(good.Login("../A.ascx"));
            this.main.Controls.Add(c);
        }
    A.ascx
    <asp:DropDownList ID="h02ddl1" runat="server" ></asp:DropDownList>D1
    <asp:DropDownList ID="h02ddl2" runat="server" ></asp:DropDownList>D2加载A.ascx时会LOAD里给D1 D2 加数据 。
    在1.aspx里如何使用联动?
      

  9.   

    a.ascx和你要加载该用户控件的窗体是无关的.
    你只要在a.ascx中实现联动就可以了.
      

  10.   

    这样不行,改变DroDdownList选择项后,会postback,由于之前加载的服务段控件A.ascx是动态加载的,后台服务器重新响应请求时,没有重新运行 
    this.main.Dispose();
    Control c = Page.LoadControl(good.Login("../A.ascx"));
    this.main.Controls.Add(c);
    这时后台没有A.ascx控件对象,更没有A.ascx里的DroDdownList控件,所以不会执行DroDdownList的SelectedIndexChanged
      

  11.   

    解决办法:
    前台<input id="booloadctrl" type="hidden" runat=server>
    <asp:LinkButton ID="h07" runat="server">/asp:LinkButton>
    后台声明对应于前台booloadctrl的控件protected System.Web.UI.HtmlControls.HtmlInputHidden booloadctrl;
    在PageLoad的if(!IsPostBack){}块之外加
    h07.Attributes["onclick"] = "document.all.booloadctrl.value='true'";
    if(booloadctrl.Value== "true")
    {
       this.main.Dispose();
       Control c = Page.LoadControl(good.Login("../A.ascx"));
       this.main.Controls.Add(c);
    }
    去掉原有h07_Click,以及隐藏代码中的给h07绑定click事件的代码。
      

  12.   

    因为是动态控件,所以要响应他的事件,肯定是需要每次都重新load的
    上面的办法是用hidden控件记录是否要load自定义控件,通过点击LinkButton调用javascript给hidden控件赋值为true,后台page_load的时候判断hidden值,为true则动态加载控件。
      

  13.   

    <input id="booloadctrl" type="hidden" runat=server>
    <asp:LinkButton ID="h07" runat="server">/asp:LinkButton>
    <asp:LinkButton ID="h08" runat="server">/asp:LinkButton>
    在PageLoad的if(!IsPostBack){}块之外加
    h07.Attributes["onclick"] = "document.all.booloadctrl.value=h07.id";if(booloadctrl.Value== "h07")
    {
    this.main.Dispose();
    Control c = Page.LoadControl(good.Login("../A.ascx"));
    this.main.Controls.Add(c);
    }
    if(booloadctrl.Value== "h08")
    {
    this.main.Dispose();
    Control c = Page.LoadControl(good.Login("../A.ascx"));
    this.main.Controls.Add(c);
    }问题:在07 08 之间如何切换改边booloadctrl.Value的值??这是个问题吧
      

  14.   

    runat="server" 下onclick好象无效
      

  15.   

    不用都不行了。没别的办法。
    erwanfan(teddyxiong) 的办法还是有问题。
    因为点击按钮后又会从新加载一次原样的ASCX。
    还是没解决问题。算了。
    还是的综合应用。
      

  16.   

    晚上没人有办法解决分就给erwanfan(teddyxiong)做辛苦费了
      

  17.   

    http://www.cnblogs.com/xucanzhao/archive/2005/09/28/246163.html
    Any problem,send me email.
      

  18.   

    经过测试对于runat="server"的LinkButton即使后台没有它绑定事件(LinkButton需已声明),点击后,还是会postback的,不过只执行了Page_Load而已。多个控件的情况也可以想办法,比如如果有07 08 两个控件,booloadctrl.Value的值设为“07,08”,后台根据之load多个控件。虽然控件每次在Page_Load重新加载,但是前台页面是有他的信息和状态的,所以当它重新加载后系统还是会根据前台post过来的状态初始化它,所以即使控件是重新load,DropDownList的SelectedIndexChanged还可以触发,SelectedIndex等还可以获得。所以如果第一个DropDownList的所有下拉选项不会因为每次重新load而发身变化的话,就可以像前面我说的那样应用,而第二个DropDownList反正它每次都是在SelectedIndexChanged中绑定的,就更没有问题。其实就是因为是点击按钮动态加载用户自定义的二级联动控件(后台代码中没有它的全局定义),所以才需要每次都重新load。只要是动态加载,即使用Ajax,仍然是需要每次都重新加载的。
      

  19.   

    public class WebUserControl1 : System.Web.UI.UserControl
    {
    protected System.Web.UI.WebControls.DropDownList dd1;
    protected System.Web.UI.WebControls.DropDownList dd2;private void Page_Load(object sender, System.EventArgs e)
    {
                 dd1.AutoPostBack = true;
    }
    override protected void OnInit(EventArgs e)
    {
    InitializeComponent();
    base.OnInit(e);
    }
    private void InitializeComponent()
    {
    this.dd1.SelectedIndexChanged += new System.EventHandler(this.dd1_SelectedIndexChanged);
    this.Load += new System.EventHandler(this.Page_Load);
    }
    private void dd1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
    Response.Write("<script>alert('1')<script>;");//这里改写成绑定dd2
    }
    }
    然后使用Control c = Page.LoadControl("WebUserControl1 ");
    this.main.Controls.Add(c); 测试时main是在form中的panel
      

  20.   

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Data.SqlClient;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;namespace TestExam
    {
    /// <summary>
    /// TestFxuan 的摘要说明。
    /// </summary>
    public class TestFxuan : System.Web.UI.Page
    {
    protected System.Web.UI.WebControls.Label Label1;
    protected System.Web.UI.WebControls.CheckBoxList CheckBoxList1;
    protected System.Web.UI.WebControls.RadioButtonList RadioButtonList1;

    private void Page_Load(object sender, System.EventArgs e)
    {
    // 在此处放置用户代码以初始化页面
    if(!this.IsPostBack)
    {
    this.RblToBind();
    this.CblToBind();
    }
    }
    private void RblToBind()
    {
    SqlConnection con=DB.CreateConn();
    con.Open();
    string SqlSet="select cTitle, cA,cB,cC,cD from Control";
    SqlDataAdapter sdr=new SqlDataAdapter(SqlSet,con);
    DataSet ds=new DataSet();
    sdr.Fill(ds,"Control");
    this.RadioButtonList1.Items.Add(ds.Tables["Control"].Rows[0][1].ToString());
                this.RadioButtonList1.Items.Add(ds.Tables["Control"].Rows[0][2].ToString());
    this.RadioButtonList1.Items.Add(ds.Tables["Control"].Rows[0][3].ToString());
    this.RadioButtonList1.Items.Add(ds.Tables["Control"].Rows[0][4].ToString());
    this.Label1.Text=ds.Tables["Control"].Rows[0][0].ToString(); this.RadioButtonList1.RepeatDirection=System.Web.UI.WebControls.RepeatDirection.Horizontal;
    this.RadioButtonList1.RepeatColumns=1;
    con.Close();
    }
    private void CblToBind()
    {
    SqlConnection con=DB.CreateConn();
    con.Open();
    string SqlSet="select cTitle, cA,cB,cC,cD from Control";
    SqlDataAdapter sdr=new SqlDataAdapter(SqlSet,con);
    DataSet ds=new DataSet();
    sdr.Fill(ds,"Control");
    this.CheckBoxList1.Items.Add(ds.Tables["Control"].Rows[0][1].ToString());
    this.CheckBoxList1.Items.Add(ds.Tables["Control"].Rows[0][2].ToString());
    this.CheckBoxList1.Items.Add(ds.Tables["Control"].Rows[0][3].ToString());
    this.CheckBoxList1.Items.Add(ds.Tables["Control"].Rows[0][4].ToString());
    this.CheckBoxList1.RepeatDirection=System.Web.UI.WebControls.RepeatDirection.Horizontal;
    this.CheckBoxList1.DataBind();
    con.Close();
    }
          
    #region Web 窗体设计器生成的代码
    override protected void OnInit(EventArgs e)
    {
    //
    // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
    //
    InitializeComponent();
    base.OnInit(e);
    }

    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {    
    this.Load += new System.EventHandler(this.Page_Load); }
    #endregion
    }
    }
    然后将主控件的AUTO什么属性设置为TRUE。。
      

  21.   

    我也来一断
    using System;
    using System.Data;
    using System.Web.UI;
    using System.Web.UI.WebControls;namespace AjaxSampleCS.Sample1
    {
      public class DropDownLink : Page
      {
        protected DropDownList countries;
        protected DropDownList states;
        protected Button submit;    private void Page_Load(object sender, EventArgs e)
        {
          
          //Make methods ed with the AjaxMethod attribute of this class
          //available to client-side calls.
          Ajax.Utility.RegisterTypeForAjax(typeof(DropDownLink));
          if (!Page.IsPostBack)
          {
            countries.DataSource = DAL.GetShippingCountries();
            countries.DataTextField = "Country";        
            countries.DataValueField = "Id";
            countries.DataBind();        countries.Items.Insert(0, new ListItem("Please Select", "0"));
          }
        }    [Ajax.AjaxMethod()]
        public DataView GetStates(int countryId)
        {
          return DAL.GetCountryStates(countryId);
        }    private void submit_Click(object sender, EventArgs e)
        {      //Rember that the states dropdown was populate client-side
          //that means it's values aren't preserved in the viewstate
          //the only way to get the selected value is the tried and tested Request.Form       
          string selectedStateId = Request.Form[states.UniqueID];
          Response.Write("You selected province/state id: " + selectedStateId);      //this also means that if we want to redisplay the form with the user's selected value, 
          //we need to do some extra work      //should do some user validation...
          states.DataSource = DAL.GetCountryStates(Convert.ToInt32(countries.SelectedIndex));
          states.DataTextField = "State";
          states.DataValueField = "Id";
          states.DataBind();
          states.SelectedIndex = states.Items.IndexOf(states.Items.FindByValue(selectedStateId));    }    #region Web Form Designer generated code
        protected override void OnInit(EventArgs e)
        {
          //
          // CODEGEN: This call is required by the ASP.NET Web Form Designer.
          //
          InitializeComponent();
          base.OnInit(e);
        }
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
          this.submit.Click += new EventHandler(this.submit_Click);
          this.Load += new EventHandler(this.Page_Load);
        }
        #endregion  }
    }
      public static DataView GetCountryStates(int countryId)
      {
          DataSet allData = GetShippingData();
          DataView statesView = allData.Tables["states"].DefaultView;
          statesView.RowFilter = "CountryId = " + countryId.ToString();
          return statesView;
      }
    前台<script language="javascript">
    //states dropdown
    var statesList = document.getElementById("<%=states.ClientID%>");//called by the onChange javascript event on the dropdown
    function LoadStates(countries)
    {
      var countryId = countries.options[countries.selectedIndex].value;
      if (countryId > 0)
      {  
        //DropDownLink is defined by Ajax.Net because that's the name of the type we registered
        DropDownLink.GetStates(countryId, LoadStates_CallBack);
      }
      else
      {
        //clear the states dropdown
        states.options.length = 0;
      }
    }
    //callback we told Ajax.Net to pass the response tos
    function LoadStates_CallBack(response)
    {
      //if the server side code threw an exception
      if (response.error != null)
      {    
        alert(response.error); //we should probably do better than this
        return;
      }  
      
      
      var states = response.value;  
      //if the response wasn't what we expected  
      if (states == null || typeof(states) != "object")
      {
        return;  
      }
        
      statesList.options.length = 0; //reset the states dropdown     
      //note that this is JavaScript casing and the L in length is lowercase for arrays
      for (var i = 0; i < states.Rows.length; ++i)
      {
        statesList.options[statesList.options.length] = new Option(states.Rows[i].State, states.Rows[i].Id);       
      }  
    }
    </script>
      

  22.   

    最后我用的是JS解决。把内容都放到JS里面做个数组进行选择。
    怎么好多人都没看贴的题目就发贴。
    AJAX吧。还是解决好多问题比较容易点。可能习惯了。