嗨:)我正在制作一个简单的表格。提示用户填写街道地址。每个用户最多可以添加5个街道地址。因此,我有5个同一个控件。我使用数据库提供所有国家和城市的列表。我正在每个国家/地区列表上收听OnSelectedItemChanged事件。触发此事件时,我将连接到数据库并将相应的City列表绑定到相应的Country ID。
所以,这很简单。我可以做5个不同的事件处理程序,但我想创建一个事件处理程序并为每个单独的Country列表项监听它。
我的国家/地区列表名为lstContactCountry1,lstContactCountry2,...最多为5,城市列表分别称为lstContactCity1,lstContactCity2。
我正在使用DropDownLists。
所以,我的问题是,当我更改所选国家/地区下拉菜单的所选项目时,除了数字1之外,城市列表根本没有数据表。仅在我更改了第一个国家/地区列表的选定项目之后,数据绑定才起作用。此外,即使我已经更改了第一个国家/地区列表中的所选项目,然后更改(例如)第二个国家/地区列表中的所选项目,两个城市列表都已绑定到同一个国家/地区,即使它们不应该“T。
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”。就这样。 :)
答案 0 :(得分:2)
您正在调用this.DataBind();
,它会绑定已绑定的页面上的所有内容(在代码后面设置数据源或在aspx代码中使用&lt;%#)。
您应该通过在绑定的实际控件上调用数据绑定来开始修复此问题。
lstContactCity.DataBind();