我有一个包含 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/