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 的第一个值。第二个列表框应该更新为相应的值,但这应该发生在所选索引更改被触发之前。那么,你能告诉我怎么做吗?

4

1 回答 1

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();     
}
于 2012-06-27T01:06:05.977 回答