Programmatically add a hyperlink to listitem
I want to have the following HTML code:
<ul><li><a href="#"></a></li></ul> I can add <li> to <ul> . But <a> to <li> impossible.
My code is:
BulletedList ul = new BulletedList(); ListItem li = new ListItem(); HyperLink hl = new HyperLink(); ul.Items.Add(li); // li has no property Controls or Items From the BulletedList, how to set a link in a ListItem , use the DisplayMode Property .
<asp:BulletedList ID="BulletedList6" runat="Server" DisplayMode="HyperLink"> <asp:ListItem Text="Los Angeles" Value="http://www.Los Angeles.aspx"></asp:ListItem> <asp:ListItem Text="Atlanta" Value="http://wwwAtlanta.aspx"></asp:ListItem> <asp:ListItem Text="San Francisco" Value="http://www.San Francisco.aspx"></asp:ListItem> </asp:BulletedList> Or in your code:
BulletedList ul = new BulletedList(); ul.DisplayMode = BulletedListDisplayMode.HyperLink; ListItem li = new ListItem(); ul.Items.Add(li); Just try this way
put a asp:Literal on the .aspx page
<asp:Literal ID="ltrInfo" runat="server"></asp:Literal> and in the base code
ltrInfo.Text = "<ul>"; ltrInfo.Text += "<li><a href='page1.aspx'>Link one</a></li>"; ltrInfo.Text += "<li><a href='page2.aspx'>Link Two </a></li>"; ltrInfo.Text += "</ul>"; The list element "li" has the properties "Text" and "Value".
You will need to create the link manually, as shown below:
string link = "<a href=\"#\">link text</a>"; and set the "Text" ListItem to a string.
If you often do this, it might be worth creating a new class that inherits from ListItem, which takes two parameters in its constructor (url and text) and automates the creation of the link.
Edit: as pointed out in another answer, you can also use the DisplayMode class of the BulletedList class for "Hyperlinks". If you go this route, you can use the ListItem Property property to specify the URL to which the link should link, and the Text property to specify the link text.