SelectedIndexChanged它是如何工作的

时间:2014-04-27 23:17:19

标签: c# asp.net

朋友们,我需要一些帮助..

我的项目中有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中选择HollyWood,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--"));
}

我发现&#34; SelectedIndexChanged&#34;使此功能生效的事件。 但我不知道这件事我以前从未工作过。

请举一些代码示例,以便我知道它是如何工作的。

1 个答案:

答案 0 :(得分: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语句来完成剩下的选择。