I have a basic list which I am using to generate a "Quick Links" menu WebPart. It looks ok but for some reason the URL field (of URL type) when rendered renders html that looks like this:

<a target="_blank" href="http://www.mysite.com, http://www.mysite.com">My Sample URL</a>

I am stumped (code below):

StringBuilder sb = new StringBuilder();            

            if (!Page.IsPostBack)
                using (SPSite site = new SPSite("http://companyweb"))
                    using (SPWeb website = site.OpenWeb())
                        SPList quickLinks = website.Lists["Quick Links"];
                        SPQuery listQuery = new SPQuery();
                        listQuery.Query = @"
                                                <FieldRef Name='Display Sequence' Ascending='True' />

                        SPListItemCollection itemCollection = default(SPListItemCollection);
                        itemCollection = quickLinks.GetItems(listQuery);

                        sb.AppendFormat("<div class=\"{0}\">", CSSClass);
                        sb.Append("<div class=\"scrollbar\"><div class=\"track\"><div class=\"thumb\"><div class=\"end\"></div></div></div></div>");
                        sb.Append("<div class=\"viewport\">");
                        sb.Append("<div class=\"overview\">");                        

                        foreach (SPListItem item in itemCollection)
                            sb.AppendFormat("<a href=\"{0}\" target=\"_blank\">{1}</a><br />", item["URL"].ToString(), item["Title"].ToString());


            return sb.ToString();

The value of an Url field is stored internally as an url/description couple. What you are fetching is the string representation of that value.

To obtain the actual values, the preferred way is to use the SPFieldUrlValue class. You need to create a new istance of the class from the field string value - you will then be able to read the desired url and description values from the returned object properties. See the example below.

SPFieldUrlValue val = new SPFieldUrlValue(item["URL"].ToString());                                
sb.AppendFormat("<a href=\"{0}\" target=\"_blank\">{1}</a><br />", val.Url, item["Title"].ToString());
  • Hi Dkong, I have edited your answer to add a little text that should help in explaining your code sample. That was to avoid your answer to be detected as low quality. Free to edit it further or roll back if you feel my change isn't correct. – Hitodama Apr 2 '13 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.