【问题标题】:How to programmatically Bind a DropDownList when the items and the SelectedValue come from separate DataTables当项目和 SelectedValue 来自不同的 DataTables 时,如何以编程方式绑定 DropDownList
【发布时间】:2015-07-02 20:13:17
【问题描述】:

例如:

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

Country Table
    CountryID (Key)
    CountryName

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

在 City 编辑页面中,您希望提供 Country DropDownList,以便当用户选择 Country 时,DropDownList 会更改 City 的 CityCountryID 字段。

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

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

CountriesDropDownList.DataBind();

【问题讨论】:

    标签: asp.net data-binding webforms


    【解决方案1】:

    我认为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();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 2018-03-21
      相关资源
      最近更新 更多