c# - 填充 asp :dropdownlist - VS 2008

标签 c# asp.net visual-studio-2008

我有一个包含 2 个 DDL 的表单

州和市

状态:

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

我尝试用这个填充城市 DDL

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

但是,我没有看到我的城市 DDL 已填充

最佳答案

我建议在保存物理对象集合的 ViewState 中创建一个私有(private)属性。然后将对象添加到该列表,然后将对象列表数据绑定(bind)到下拉列表。

后页

<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 属性上采用延迟加载,因此您在访问列表时永远不会遇到空引用异常。

关于c# - 填充 asp :dropdownlist - VS 2008,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/299969/

相关文章:

c# - 事件目录的角色安全

c# - Bootstrap Style & Surrounding Div 标签来自 ASP.NET Code Behind

c# - 使用 C# 在 Windows CE 5.0 中创建文件

c# - ASP.NET MVC 中的 HttpClient 单例实现

c# - 在不处于 Debug模式的情况下获取导致程序崩溃的异常

c# - 跳出 finally block

c# - web.config 连接字符串在发布时更改

c++ - mt.exe : general error c101008d: Failed to write the updated manifest to the resource of file . .. 访问被拒绝

xml - 什么是使用 VB.net 2008 编写 XML 的好例子

c# - ASP.net Identity 2.0 注销另一个用户