2012-06-27 50 views
0

我有2个列表框。根据第一个列表框中的选定值填充第二个列表框

  <asp:ListBox ID="ListBox_Region" runat="server" 
       DataTextField="arregion" DataValueField="arregion" AutoPostBack="True" 
      Height="96px" 
      Width="147px" DataSourceid="sqldatasource1"></asp:ListBox> 
      <asp:ListBox ID="ListBox_Area" runat="server" 
      DataTextField="ardescript" DataValueField="ardescript"  
      AutoPostBack="True"    
      OnSelectedIndexChanged="ListBox_Area_SelectedIndexChanged" 
      Height="96px" 
      Width="147px" > 

所以,当我选择ListBox_Region的值,相应的值得到ListBox_Area更新以这样的方式

 protected void ListBox_Region_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     this.ListBox_Area.Items.Clear(); 
     string selectedRegion = ListBox_Region.SelectedValue; 
     var query = (from s in DBContext.areas 
        where s.arregion == selectedRegion 
        select s); 
     ListBox_Area.DataSource = query; 
     ListBox_Area.DataBind(); 


    } 

为ListBoxRegion_SelectedIndexChaged该事件被写在页面加载。

但是,问题出现在初始页面加载,其中ListBox_Region的第一个值应该被默认选中。第二个列表框应该更新为相应的值,但这应该发生在选定的索引更改被触发之前。所以,你可以让我知道如何做到这一点?

回答

0

ListBox_Region_SelectedIndexChanged上的逻辑移动到一个分离的方法,并在回发为false时从page_load进行调用。

protected void Page_Load(object sender, EventArgs e) 
{ 
    if(!Page.IsPostBack) 
    { 
      // Bind ListBox_Region and set the first value as selected 
      ... 
      // 
      BindAreaList(); 
    } 
} 

protected void ListBox_Region_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    BindAreaList(); 
} 

protected void BindAreaList() 
{ 
    this.ListBox_Area.Items.Clear(); 
    string selectedRegion = ListBox_Region.SelectedValue; 
    var query = (from s in DBContext.areas 
       where s.arregion == selectedRegion 
       select s); 
    ListBox_Area.DataSource = query; 
    ListBox_Area.DataBind();  
} 
相关问题