こんにちは:)簡単なフォームを作っています。ユーザーは住所を入力するよう求められます。すべてのユーザーは、最大 5 つの住所を追加できます。したがって、私は5つの同じコントロールを持っています。データベースを使用して、すべての国と都市のリストを提供しています。すべての国リストで OnSelectedItemChanged イベントをリッスンしています。このイベントがトリガーされると、データベースに接続し、対応する都市リストを適切な国 ID にバインドします。
したがって、それはかなり単純です。5 つの異なるイベント ハンドラーを実行できますが、イベント ハンドラーを 1 つだけ作成して、Country リスト項目ごとにそれをリッスンしたいと考えました。
My Country リストは lstContactCountry1、lstContactCountry2、... 5 までと呼ばれ、City リストはそれぞれ lstContactCity1、lstContactCity2 と呼ばれます。
私はドロップダウンリストを使用しています。
したがって、私の問題は、国ドロップダウンの選択項目を変更すると、番号 1 を除いて、都市リストがまったくデータバインドされていないことです。データバインディングは、最初の国リストの選択した項目を一度変更した後にのみ機能します。さらに、最初の国リストの選択項目を一度変更してから、たとえば 2 番目の国リストの選択項目を変更したとしても、両方の都市リストが同じ国にバインドされている必要があります。だ。
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」を追加してしまいました。それで全部です。:)