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

时间:2012-06-27 00:53:37

标签: c# asp.net listbox

我有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的事件写在页面Load。

但是,问题在于初始页面加载,默认情况下应该选择ListBox_Region的第一个值。第二个列表框应该更新为相应的值,但这应该在选定的索引更改被触发之前发生。那么,请你告诉我怎么做?

1 个答案:

答案 0 :(得分:0)

ListBox_Region_SelectedIndexChanged上的逻辑移至分离的方法,并在回发为假时从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();     
}