开发者

how to add an OnClick event on DropDownList's ListItem that is added dynamically?

Say I have the following code:

        DropDownList changesList = new DropDownList();

        ListItem item;

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

How do you dynamically add an OnClick event to item so开发者_如何转开发 that google.com will be visited after clicking on the item?


Add this to your code:

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;");


First declare the dropdownlist

 <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>

Second, in the code behind put this code

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

Hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜