C# ASP.Net Web Form--DropDownList

點擊前一DropDownList,動態建立後一DropDownList選項

Step 1. 拖曳兩個DropDownList

AutoPostBack屬性設為True

Step 2. DropDownList1加入選項
Step 3. 雙擊DropDownList1,code behind新增SelectedIndexChanged事件
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList2.Items.Clear(); //清除DropDownList控制項之所有項目

            //DropDownList1選擇改變,動態建立相對應之選項(DropDownList2項目)
            switch (DropDownList1.SelectedValue)
            {
                case "0":
                    DropDownList2.Items.Add(new ListItem("請先選擇區域","0"));
                    DropDownList2.Enabled = false;
                    break;
                case "a":
                    DropDownList2.Items.Add(new ListItem("請先選擇區域", "0"));
                    DropDownList2.Items.Add(new ListItem("a1","a1"));
                    DropDownList2.Items.Add(new ListItem("a2","a2"));
                    DropDownList2.Enabled = true;
                    break;
                case "b":
                    DropDownList2.Items.Add(new ListItem("請先選擇區域", "0"));
                    DropDownList2.Items.Add(new ListItem("b1","b1"));
                    DropDownList2.Items.Add(new ListItem("b2","b2"));
                    DropDownList2.Enabled = true;
                    break;
                case "c":
                    DropDownList2.Items.Add(new ListItem("請先選擇區域", "0"));
                    DropDownList2.Items.Add(new ListItem("c1","c1"));
                    DropDownList2.Items.Add(new ListItem("c2","c2"));
                    DropDownList2.Enabled = true;
                    break;
            }
        }