简体   繁体   中英

Populate second listbox based on the selected value from first listbox

I have 2 list boxes.

           <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" >

So, when I select a value from ListBox_Region , the corresponding values get updated in ListBox_Area in this way:

        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();


    }

The event for ListBoxRegion_SelectedIndexChaged is written in page Load.

However, the problem is on initial page load, where the first value of ListBox_Region should be Selected by default. The second listbox should be updated to corresponding values but this should happen before selected index changed gets fired. So, can u please let me know how to do this?

Move the logic on ListBox_Region_SelectedIndexChanged to a separated method and call it from page_load when postback is false.

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();     
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM