2014-04-27 56 views
-2

朋友我需要一些幫助..的SelectedIndexChanged它是如何工作

我有4個DropDownList的在我的項目

我告訴你標記他們兩個..

<asp:DropDownList ID="DropDwonList1" runat="server"> 
<asp:ListItem Text="--Select Region--" Selected="True"></asp:ListItem> 
<asp:ListItem Text="HollyWood" Value="HollyWood"></asp:ListItem> 
    <asp:ListItem Text="BollyWood" Value="BollyWood"></asp:ListItem> 
<asp:ListItem Text="Farance" Value="Farance"></asp:ListItem> 
</asp:DropDownList> 

DropDwonList2被綁定與DB

<asp:DropDownList ID="DropDwonList2" runat="server" /> 

我想,如果我從DropDwonList1的DropDwonList2選擇好萊塢只顯示好萊塢演員姓名 如果我選擇boolyWood DropDwonList2只顯示寶萊塢演員的名字。

public void BindDDL_ActorName_RegionOne() 
{ 
    string query = "Select ID, Actor_Name from Actor where Region_Id=1"; 
    SqlConnection con = new SqlConnection(conStr); 
    SqlDataAdapter da = new SqlDataAdapter(query, con); 
DataTable dt = new DataTable(); 
da.Fill(dt); 
DropDwonList2.DataSource = dt; 
DropDwonList2.DataTextField = "Name"; 
DropDwonList2.DataValueField = "ID"; 
DropDwonList2.DataBind(); 
DropDwonList2.Items.Insert(0, new ListItem("--Select Name--")); 
} 

public void BindDDL_ActorName_RegionTwo() 
{ 
    string query = "Select ID, Actor_Name from Actor where Region_Id=2"; 
SqlConnection con = new SqlConnection(conStr); 
SqlDataAdapter da = new SqlDataAdapter(query, con); 
DataTable dt = new DataTable(); 
da.Fill(dt); 
DropDwonList2.DataSource = dt; 
DropDwonList2.DataTextField = "Name"; 
DropDwonList2.DataValueField = "ID"; 
DropDwonList2.DataBind(); 
DropDwonList2.Items.Insert(0, new ListItem("--Select Name--")); 
} 

public void BindDDL_ActorName_RegionThree() 
{ 
    string query = "Select ID, Actor_Name from Actor where Region_Id=3"; 
SqlConnection con = new SqlConnection(conStr); 
SqlDataAdapter da = new SqlDataAdapter(query, con); 
DataTable dt = new DataTable(); 
da.Fill(dt); 
DropDwonList2.DataSource = dt; 
DropDwonList2.DataTextField = "Name"; 
DropDwonList2.DataValueField = "ID"; 
DropDwonList2.DataBind(); 
DropDwonList2.Items.Insert(0, new ListItem("--Select Name--")); 
} 

我發現「SelectedIndexChanged」事件使此功能處於活動狀態。 但我不知道這個事件我從來沒有工作過現在。

請在代碼中加上一些例子,以便我知道它是如何工作的。

回答

0

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.selectedindexchanged(v=vs.110).aspx

您需要

OnSelectedIndexChanged="Index_Changed" 
AutoPostBack="true" 

添加到您的

<asp:DropDownList ID="DropDwonList1" runat="server"> 

所以它看起來像

<asp:DropDownList ID="DropDwonList1" runat="server" OnSelectedIndexChanged="Index_Changed" AutoPostBack="true"> 

在C#中,您將代碼添加一個函數爲這個指數變化

protected void Index_Changed(Object sender, EventArgs e) { 
    //Put logic to figure out what needs to be selected 
} 

對於邏輯分析,你可以做類似

if(DropDwonList1.SelectedValue.Text.Equals("HollyWood")){ 
    BindDDL_ActorName_RegionOne(); 
} 

,然後明明只是寫其他if/else語句,完成了剩餘的選擇。

+1

另外,當您希望選擇立即發生時,您只需要autopostback。如果您有一種情況需要更改多個下拉列表,並且不希望每次更改時重新加載頁面,只需將其設置爲false,並使按鈕或某個其他元素觸發回發。 – Newyork167

+0

非常棒,非常感謝 – fungus

相關問題