如何在动态添加的DropDownList列表项上添加OnClick事件?

时间:2011-09-23 02:37:54

标签: c# asp.net

说我有以下代码:

        DropDownList changesList = new DropDownList();

        ListItem item;

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

如何向item动态添加OnClick事件,以便点击item后访问google.com?

2 个答案:

答案 0 :(得分: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;");

答案 1 :(得分: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);
    }
}

希望这有帮助