2011-09-23 4 views
3

다음 코드가 있다고 가정 해보십시오.동적으로 추가 된 DropDownList의 ListItem에 OnClick 이벤트를 추가하는 방법은 무엇입니까?

  DropDownList changesList = new DropDownList(); 

     ListItem item; 

     item = new ListItem(); 
     item.Text = "go to google.com"; 
     changesList.Items.Add(item); 

item를 클릭 한 후 google.com을 방문하도록 OnClick 이벤트를 item에 동적으로 추가하는 방법은 무엇입니까?

+0

하는 데 도움이 아마도'changesList.SelectedIndex가 필요합니다. 변경된 + = ' – draw

답변

4

코드에 이것을 추가

DropDownList changesList = new DropDownList(); 

ListItem item; 
item = new ListItem(); 
item.Text = "go to google.com"; 
item.Value = "http://www.google.com"; 

changesList.Items.Add(item); 
changesList.Attributes.Add("onChange", "location.href = this.options[this.selectedIndex].value;"); 
+0

감사합니다 ~ – draw

0

먼저

<asp:DropDownList ID="ddlDestination" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddl_SelectedIndexChanged"> 
    <asp:ListItem Text="Select Destination" Selected="True" /> 
    <asp:ListItem Text="Go To Google.com" Value="http://www.google.com" /> 
    <asp:ListItem Text="Go To Yahoo.com" Value="http://www.yahoo.com" /> 
    <asp:ListItem Text="Go To stackoverflow.com" Value="http://www.stackoverflow.com" /> 
</asp:DropDownList> 

두 번째 드롭 다운리스트를 선언 뒤에이 코드를 넣어 코드에서

protected void ddl_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    if (ddlDestination.SelectedIndex > 0) 
    { 
     string goToWebsite = ddlDestination.SelectedValue; 
     Response.Redirect(goToWebsite); 
    } 
} 

희망이

+1

이 도움이 될 수도 있습니다. 하지만 내 질문에'DropDownList의 ListItem은 "동적으로"추가 되었습니까? "감사합니다. – draw

관련 문제