Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programmatically add hyperlink to listitem

Tags:

html

c#

asp.net

I want to have the following HTML programmatically:

<ul><li><a href="#"></a></li></ul>

I can add <li> to <ul>. But <a> to <li> is not possible.

My code:

    BulletedList ul = new BulletedList();    
    ListItem li = new ListItem();    
    HyperLink hl = new HyperLink();
    ul.Items.Add(li);
    // li has no property Controls or Items
like image 307
Ozkan Avatar asked Nov 03 '11 16:11

Ozkan


3 Answers

From BulletedList, how to set link in 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);
like image 60
Jon Adams Avatar answered Nov 18 '22 10:11

Jon Adams


Just try this way

place a asp:Literal in your .aspx page

<asp:Literal ID="ltrInfo" runat="server"></asp:Literal>

and in the backend 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>";
like image 22
huMpty duMpty Avatar answered Nov 18 '22 10:11

huMpty duMpty


Your list item 'li' has the properties of 'Text' and 'Value'.

You will need to create the link manually, similar to the following:

string link = "<a href=\"#\">link text</a>";

and set the 'Text' of the ListItem to the string.

If this is something you do often, it may be worth creating a new class that inherits from ListItem that accepts two parameters in it's constructor (url and text) and automates the creation of the link.

Edit: As indicated by another answer, you may also want to use the BulletedList class's DisplayMode of 'Hyperlink'. If you take this route, you can use the ListItem's 'Value' property to specify the URL the link should go to, and the 'Text' property to specify the link text.

like image 1
Jeff Avatar answered Nov 18 '22 10:11

Jeff