ASP.NET和C#中的动态下拉列表

3

我将尝试使用两个下拉列表绑定数据。

我在SQL Server 2008中创建了2个表:

1)country:

country_id (primary key)
country_name

2) 状态:

state_id(primary key)
state_name
country_id(foreign_key)

现在我尝试将数据绑定到 2 个下拉列表框 ddp1 和 ddp2 上,当我从第一个下拉列表(ddp1)中选择国家时,应该在第二个下拉列表(ddp2)中显示相应的州列表。 请问有人可以帮助我实现这个功能吗? 谢谢。
4个回答

1

您可以使用更新面板来实现此操作。

1)将两个控件放入更新面板中。 2)将第一个下拉列表的autopostback属性设置为true。 3)为下拉列表添加触发器,使用EventName="SelectedIndexChanged"。 4)然后在代码后台中编写一个函数来处理第一个下拉列表的SelectedIndexChanged事件。在该函数中,绑定第二个下拉列表的数据。

它大致看起来像这样(注意:未经测试)

<asp:UpdatePanel runat="server" ID="update1" UpdateMode="Conditional">
    <asp:Dropdownlist runat="server" ID="firstddl" AutoPostBack="True"/>
    <asp:Dropdownlist runat="server" ID="secondddl" />
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="firstddl" EventName="SelectedIndexChanged" />
    </Triggers>
</asp:UpdatePanel>

代码后台(再次未经测试)

Protected Sub firstddl_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles firstddl.SelectedIndexChanged
    'Update secondddl here
End Sub

1

最佳且简单的方法

<asp:DropDownList ID="ddlCountry" runat="server" DataSourceID="odsCountry"              
    DataTextField="CountryName" DataValueField="CountryID" AutoPostBack="True">                                              </asp:DropDownList>                                                         
<asp:ObjectDataSource ID="odsCountry" runat="server" SelectMethod="GetAllCountry"
TypeName=""></asp:ObjectDataSource>


<asp:DropDownList ID="ddlRegion" runat="server" DataSourceID="odsRegion"                                                          DataTextField="StateName" DataValueField="StateID">                                                                     </asp:DropDownList>
<asp:ObjectDataSource ID="odsRegion" runat="server" SelectMethod="GetStateByCountryID"
     TypeName="Core.BLL.State">
     <SelectParameters>
<asp:ControlParameter ControlID="ddlCountry" Name="countryID" 
PropertyName="SelectedValue" Type="Int32" />                                                                
     </SelectParameters>
</asp:ObjectDataSource>

0

在你了解了在ddp1中选择的“country”的值之前,你将无法将“state”绑定到ddp2。

为了实现您想要的效果,您可以使用JavaScript(理想情况下是jQuery)在第一个下拉列表中选择值后填充第二个下拉列表。这可以通过在客户端创建包含所有数据的数组或执行ajax回调以从服务器获取状态数据来完成。

另一种选择是在第一个下拉列表更改时对服务器执行“自动发布回发”以填充第二个下拉列表。


0

做出大量的假设,但确保ddp1.textdatafield =“country_name”,ddp1.valuedatafield =“country_id”

确保ddp2.textdatafield =“state_name”,ddp2.valuedatafield =“state_id”

将indexchanged事件连接到ddp1。您在ddp1上选择的indexchanged事件应调用存储过程/查询,以返回所有行状态表中的国家ID(外键)= ddp1.selectedindex值,并将其用作第二个dd列表的数据源。

我认为当使用sql/objectdatasource控件时,可以通过将第二个dd列表的输入参数指定为第一个dd列表的selectedvalue来自动连接此操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接