본문 바로가기

프로그래밍/.NET

[ASP.NET] DropDownList ListItem 선택 시 이벤트 발생

반응형

DropDownList 드롭다운 리스트에서 아이템 클릭 시 이벤트를 발생시켜보자



OnSelectedIndexChanged 속성을 이용 시 서버 단에서 이벤트를 처리할 수 있다.

OnChange 속성을 이용 시 스크립트 단에서 이벤트를 처리할 수 있다.



OnSelectedIndexChanged 의 예제를 살펴보자


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<td>
    <asp:DropDownList ID="ddl_Grade" runat="server" OnSelectedIndexChanged="SubjectChange" AutoPostBack="true">
        <asp:ListItem Value="1">1</asp:ListItem>
        <asp:ListItem Value="2">2</asp:ListItem>
        <asp:ListItem Value="3">3</asp:ListItem>
        <asp:ListItem Value="4">4</asp:ListItem>
        <asp:ListItem Value="5">5</asp:ListItem>
        <asp:ListItem Value="6">6</asp:ListItem>
    </asp:DropDownList>
</td>
<td>
    <asp:DropDownList ID="ddl_Subject" runat="server">
        <asp:ListItem Value="1">국어</asp:ListItem>
        <asp:ListItem Value="2">수학</asp:ListItem>
        <asp:ListItem Value="3">통합</asp:ListItem>
        <asp:ListItem Value="4" Enabled="false">사회</asp:ListItem>
        <asp:ListItem Value="5" Enabled="false">과학</asp:ListItem>
    </asp:DropDownList>    
</td>
cs


학년 드롭박스와 과목 드롭박스가 있다.


여기서 학년의 드롭박스의 아이템(학년)을 선택 시 이벤트가 발생한다.

즉, 서버단의 SubjectChange 함수를 타게된다.


현재 과목 드롭박스의 리스트는 국어, 수학, 통합이 보여지는 상태이다.

여기서! 3학년 클릭 시 국어, 수학, 통합이 아닌 국어, 수학, 사회, 과학이 보여지도록 이벤트 처리를 해보자


1
2
3
4
5
6
7
8
9
protected void SubjectChange(object sender, EventArgs e)
{
    if (this.ddl_Grade.SelectedValue == "3")
    {
        this.ddl_Subject.Items[2].Enabled = false;// '통합'과목 숨기기
        this.ddl_Subject.Items[3].Enabled = true// '사회'과목 보이기
        this.ddl_Subject.Items[4].Enabled = true// '과학'과목 보이기
    }
}
cs



반응형