Ozkan
Ozkan

Reputation: 2041

programmatically add hyperlink to listitem

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

Upvotes: 6

Views: 19048

Answers (3)

Jeff
Jeff

Reputation: 2871

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.

Upvotes: 1

Jon Adams
Jon Adams

Reputation: 25137

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

Upvotes: 13

huMpty duMpty
huMpty duMpty

Reputation: 14460

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

Upvotes: 5

Related Questions