Thursday, December 22, 2011

Programmatically add a user-friendly name in place of a hyperlink in a SPListItem Link field

There may come a time in which you would like to specify concise, user-friendly text instead of the hyperlink itself within a hyperlink field/column contained in a SharePoint list.  To do this, you simply add a comma followed by a space within your hyperlink field between the URL and text you wish to display and SharePoint will display the text after the comma as opposed to the hyperlink (i.e. "http://www.google.com/, Click here to go to Google").  Naturally, if the user clicks on the link, he/she will be redirected to the url specified in your hyperlink field.  In this example, I'm inserting a new SPListItem into a custom SPList and updating the hyperlink field, called Link, to display "Sherman's Blog" as opposed to the url, http://shermanstechnicalblog.blogspot.com/.  Here is sample code that demonstrates this technique:

            string blogTitle = "Sherman's Blog";
            string blogUrl = "http://shermanstechnicalblog.blogspot.com/";
            using (SPSite rootSite = new SPSite(rootSiteUrl))
            {
                using (SPWeb rootWeb = rootSite.OpenWeb())
                {
                    SPList blogList = rootWeb.Lists["Blog Directory"];
                    SPListItem item = blogList.Items.Add();
                    item["Title"] = "My Blog";
                    item["Link"] = string.Format("{0}, {1}", blogTitle, blogUrl);
                    item.Update();
                }
            }

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.