首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当项和DropDownList来自不同的DataTables时,如何以编程方式绑定DataTables

当项和DropDownList来自不同的DataTables时,如何以编程方式绑定DataTables
EN

Stack Overflow用户
提问于 2015-07-02 20:13:17
回答 1查看 46关注 0票数 0

例如:

您有2 DataTables,城市和乡村:

代码语言:javascript
运行
复制
Country Table
    CountryID (Key)
    CountryName

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

在“城市”编辑页面中,您希望提供一个Country DropDownList,以便当用户选择一个国家时,DropDownList会更改城市的CityCountryID字段。

代码语言:javascript
运行
复制
CountriesDropDownList.DataSource = GetCountriesDataTable();
CountriesDropDownList.DataTextField = "CountryName";
CountriesDropDownList.DataValueField = "CountryID";

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

CountriesDropDownList.DataBind();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-02 20:28:06

我不认为DropDownList具有SelectedValueDataSourceSelectedValueField属性。相反,一旦用户选择了国家,就可以使用OnSelectedIndexChanged事件绑定城市列表。

样本代码:

ASPX

代码语言:javascript
运行
复制
<asp:DropDownList ID="CountriesDropDownList" runat="server" OnSelectedIndexChanged="CountriesDropDownList_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
<asp:DropDownList ID="CitiesDropDownList" runat="server"></asp:DropDownList>

代码隐藏

代码语言:javascript
运行
复制
    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();
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31193837

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档