Adding Hyperlinks programmatically to a list in SharePoint

A common problem, how do I add Hyperlinks to a list programmatically in SharePoint

The documentation (SharePoint SDK) does give a clue to the answer but no real examples. You will see that the Hyperlink field is a System.String, System.String. It also states below ‘The URL field uniquely consists of two strings separated by a comma and space. One string contains the URL path and the other contains the description used as hyperlinked text.’

Sample code:

   SPSite site = new SPSite(url);
   SPWeb web = site.OpenWeb();
   SPList list = web.Lists[listName];
   SPListItem item = list.Items.Add();
   item["Hyperlink"] = stringUrl + “, ” + stringDescription;
   item.Update();

The important bit is the seperating “, ” (note comma and a space).

Also the hyperlink cannot be relative and must have http:// and is validated to ensure it is a valid hyperlink.

Update: Provided by ThatGuyGreg

Things get easier in MOSS 2007/WSS V3

SPFieldUrlValue linkUrl = new SPFieldUrlValue();
linkUrl.Description = “Whatever”;
linkUrl.Url = anURL.ToString();
anItem["URL"] = linkUrl;
anItem.Update();

This entry was posted in Development, SharePoint and tagged , , . Bookmark the permalink.
  • Petter

    Thanks, you saved me a lot of headache :)

  • ThatGuyGreg

    Just an update to this for MOSS 2007…

    SPFieldUrlValue linkUrl = new SPFieldUrlValue();
    linkUrl.Description = “Whatever”;
    linkUrl.Url = anURL.ToString();
    anItem["URL"] = linkUrl;
    anItem.Update();