当项目和 SelectedValue 来自单独的数据表时如何以编程方式绑定 DropDownList

How to programmatically Bind a DropDownList when the items and the SelectedValue come from separate DataTables

例如:

你有 2 个数据表,城市和国家:

Country Table
    CountryID (Key)
    CountryName

City Table
    CityID (Key)
    CityName
    CityCountryID (FK to Country)

在城市编辑页面中,您想提供一个国家/地区下拉列表,以便在用户选择国家/地区时,下拉列表会更改城市的 CityCountryID 字段。

CountriesDropDownList.DataSource = GetCountriesDataTable();
CountriesDropDownList.DataTextField = "CountryName";
CountriesDropDownList.DataValueField = "CountryID";

// How to do this?
CountriesDropDownList.SelectedValueDataSource = GetCitiesDataTable(); //error
CountriesDropDownList.SelectedValueField = "CityCountryID"; //error

CountriesDropDownList.DataBind();

我认为 DropDownList 没有 SelectedValueDataSourceSelectedValueField 属性。相反,您可以在用户选择国家/地区后使用 OnSelectedIndexChanged 事件绑定城市列表。

示例代码:

ASPX

<asp:DropDownList ID="CountriesDropDownList" runat="server" OnSelectedIndexChanged="CountriesDropDownList_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
<asp:DropDownList ID="CitiesDropDownList" runat="server"></asp:DropDownList>

代码隐藏

    protected void Page_Load(object sender, EventArgs e)
    {
        CountriesDropDownList.DataSource = GetCountriesDataTable();
        CountriesDropDownList.DataTextField = "CountryName";
        CountriesDropDownList.DataValueField = "CountryID";
        CountriesDropDownList.DataBind();        
    }
    protected void CountriesDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        string selectedCountry = CountriesDropDownList.SelectedValue;
        CitiesDropDownList.DataSource = GetCitiesDataTable(selectedCountry);
        CitiesDropDownList.DataTextField = "CityName";
        CitiesDropDownList.DataValueField = "CityID";
        CitiesDropDownList.DataBind();
    }