Linking Selected Items

Linking Selected Items

Controls featured in this example:

  • Sitecore Web Control

Classes featured in this example:

  • Sitecore.Context
  • Sitecore.Data.Database
  • Sitecore.Data.Fields.MultilistField
  • Sitecore.Data.Items.Item
  • Sitecore.Links.LinkManager
  • System.Text.StringBuilder

Linking Selected Items C# Web Control Code

//get List Fields metadata item from context database using item guid
Sitecore.Data.Database db = Sitecore.Context.Database;
Sitecore.Data.Items.Item item = db.GetItem("{7246223A-BFB0-41F9-8A91-1E7D931CDC43}");
if (item == null) return;

Sitecore.Data.Fields.MultilistField multilistFld = item.Fields["example multilist"];
if (multilistFld == null) return;

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.Write("C# Web Control Real-time Output");
output.RenderEndTag();

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-size:x-small; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.P);
//using : for colon and   for space
output.Write("{0}: {1}", "Item", item.DisplayName);
output.RenderEndTag(); //P

output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.P);
output.Write("{0}{1}", multilistFld.InnerField.DisplayName, " Selected Items");

output.RenderEndTag(); //P

System.Text.StringBuilder itemDisplay = new System.Text.StringBuilder("<div>");
if (multilistFld.GetItems().Length > 0)
{
    foreach (Sitecore.Data.Items.Item listItem in multilistFld.GetItems())
    {   
        itemDisplay.Append(string.Format(@"<a href={0}>{1}</a>", Sitecore.Links.LinkManager.GetItemUrl(listItem), listItem.Name));
        itemDisplay.Append("</br>");
    } 

itemDisplay.Append("</div>");
string listDisplay = itemDisplay.ToString();
output.Write(listDisplay);
output.RenderEndTag(); //Div

Linking Selected Items C# Web Control Output

Example Multilist Selected Items