【问题标题】:ASP.NET Data binding not working properly OnSelectedItemChanged eventASP.NET 数据绑定无法正常工作 OnSelectedItemChanged 事件
【发布时间】:2013-08-28 09:57:47
【问题描述】:

嗨 :) 我正在制作一个简单的表格。提示用户填写街道地址。每个用户最多可以添加 5 个街道地址。因此,我有 5 个相同的控件。我正在使用数据库来提供所有国家和城市的列表。我正在收听每个国家/地区列表上的 OnSelectedItemChanged 事件。触发此事件时,我将连接到数据库并将相应的城市列表绑定到相应的国家/地区 ID。

所以,这相当简单。我可以做 5 个不同的事件处理程序,但我只想创建一个事件处理程序并为每个国家列表项监听它。

我的国家/地区列表称为 lstContactCountry1、lstContactCountry2、...直到第 5 位,而城市列表分别称为 lstContactCity1、lstContactCity2。

我正在使用下拉列表。

所以,我的问题是,当我更改任何国家下拉列表的选定项目时,除了数字 1,城市列表根本没有数据绑定。只有在我更改了第一个国家/地区列表的选定项目一次后,数据绑定才有效。此外,即使我已经更改了第一个国家/地区列表的选定项目,然后更改,例如,第二个国家/地区列表的选定项目,他们的城市列表已经绑定到同一个国家,即使他们应该不。

ASP.NET 代码隐藏:

protected void lstContactCountry1_SelectedIndexChanged(object sender, EventArgs e)
    {
        // lstContactCountry is the sender of the event
        DropDownList lstContactCountry = sender as DropDownList;

        // Get the number of DropDownList
        char lstNumber = lstContactCountry.ID[lstContactCountry.ID.Length - 1];
        lblTemp.Text = "Sender: " + lstContactCountry.ID;

        // Get the IdCountry property from the selected value of the DropDownList
        string idCountry = lstContactCountry1.SelectedValue;

        // Some ADO.NET code :)
        DataSet dataSet = new DataSet();
        SqlConnection connection = new SqlConnection(connectionString);
        SqlDataAdapter adapter = new SqlDataAdapter("SELECT IdCity, CityName FROM City WHERE IdCountry = '" + idCountry + "' ORDER BY CityName", connection);

        adapter.Fill(dataSet, "City");

        // lstContactCity is the City DropDownList below the selected Country DropDownList
        DropDownList lstContactCity = this.Master.FindControl("phSecuredPageMainContent").FindControl("lstContactCity" + lstNumber.ToString()) as DropDownList;
        lblTemp.Text += "<br />Receiver: ";

        lstContactCity.DataSource = dataSet.Tables["City"];
        lstContactCity.DataTextField = "CityName";
        lstContactCity.DataValueField = "IdCity";

        this.DataBind();

        // Adding a default value to the list
        lstContactCity.Items.Insert(0, new ListItem("City", "0"));
        lstContactCity.SelectedIndex = 0;           
    }

编辑: 我发现了错误。就在这行代码:

        string idCountry = lstContactCountry1.SelectedValue;

我无意中在控件名称的末尾添加了一个“1”。就这样。 :)

【问题讨论】:

标签: asp.net data-binding drop-down-menu


【解决方案1】:

您正在调用this.DataBind();,它将数据绑定页面上已绑定的所有内容(数据源设置在代码后面或

您应该通过在您正在绑定的实际控件上调用 databind 来开始解决此问题。

lstContactCity.DataBind();

【讨论】:

  • 感谢您的快速回复!我按照您告诉我的方式更改了代码,但仍然无法正常工作:(
  • 我发现了错误,并将其写在问题描述的底部。顺便说一句,this.DataBind() 绑定了页面上所有使用数据绑定的元素是对的,但它仍然可以(视觉上)绑定整个页面。所以,这绝对不是问题。顺便说一句,我修复了这一行,因为绑定整个页面确实没有意义。所以,毕竟 - 再次感谢:)
猜你喜欢
  • 1970-01-01
  • 2015-09-28
  • 2013-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多