2012-06-27 54 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();  
} 
相關問題