2008-11-18 55 views
1

我有表格2 DDL命名填充的asp:下拉列表 - VS 2008

國家和城市

國家:

<asp:UpdatePanel ID="States" runat="server" UpdateMode="Conditional"> 
     <Triggers> 
      <asp:AsyncPostBackTrigger ControlID="States"EventName="SelectedIndexChanged" /> 
     </Triggers> 
     <ContentTemplate> 
      <asp:DropDownList ID="States" runat="server" 
      AutoPostBack="True" DataSourceID="StatesObjectDataSource" 
      AppendDataBoundItems="true" 
       onselectedindexchanged="States_SelectedIndexChanged"> 
      <asp:ListItem Value="-1" Text="- None -"/>  
      </asp:DropDownList> 
      <asp:ObjectDataSource ID="StatesObjectDataSource" runat="server" 
       onselecting="StatesObjectDataSource_Selecting" 
       SelectMethod="GetStates" 
       TypeName="Something"> 
      </asp:ObjectDataSource> 
     </ContentTemplate> 
    </asp:UpdatePanel> 

市:

<asp:DropDownList ID="Cities" runat="server"> 
     </asp:DropDownList> 

當他們選擇狀態我想爲該州的所有城市填充城市DDL。

在代碼後面,我走不到

States_SelectedIndexChanged(object sender, EventArgs e) 

,我試圖通過這個

Cities.Items.Add(new ListItem(city,city)); 

填充城市DDL不過,我沒有看到我的城市DDL填充

回答

2

我建議在ViewState中創建一個包含物理對象集合的私有屬性。然後將該對象添加到該列表,然後將對象列表數據綁定到下拉列表中。

頁背後

<asp:DropDownList runat="server" ID="ddlCity" DataValueField="Key" DataTextField="Value"> 
</asp:DropDownList> 

代碼隱藏

private List<KeyValuePair<string, string>> ListData 
{ 
    get { return (List<KeyValuePair<string, string>>) (ViewState["ListData"] ??  
       (ViewState["ListData"] = new List<KeyValuePair<string, string>>())); } 
    set { ViewState["ListData"] = value; } 
} 

protected void States_SelectedIndexChanged_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    ListData.Add(new KeyValuePair<string, string>(ddlCitys.SelectedValue, ddlCitys.SelectedValue)); 
    ddlCitys.DataSource = ListData; 
    ddlCitys.DataBind(); 
} 

Get語句還通過在listData屬性延遲加載,以便訪問列表中時,你會不會遇到一個空引用異常。

1

如果可能,我建議使用CascadingDropDown Extender而不是UpdatePanel。沒有必要重新發明這個輪子,Toolkit控件使用Web服務而不是部分回發(更快)。

+0

Dave:我使用SUBSONIC數據訪問層獲取我的數據,但沒有webservice。 CascadingDropDown擴展器是否仍然可以使用List <>對象。另外,您是否可以介紹一下爲什麼通過Update Panel推薦它? – user38230 2008-11-19 10:55:31

1

在更新面板中放置您的城市DropDownList。