in

Melyssa’s Blog

SharePoint Field Data: Simple Web Part

If you're working with CAML, it's good to have available a list of fields, their internal field names, and their data types. I wrote a simple Web part that accepts the display name of a list and returns this information, along with whether or not each field is required or indexed. The code for the Web part can be found below, and can easily be tweaked to include other field data. I went ahead and retrieved the field data for many common lists in SharePoint as a reference, and have included those results in the attached SharePoint Lists Field Data document.

   

    public class GetListFieldInfo : System.Web.UI.WebControls.WebParts.WebPart
    {
        private const string default_listname = "Documents";
        private string listname;
       
        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true), WebDisplayName("List Name"), WebDescription("Enter the display name of the list.")]
        public string ListName
        {
            get { return listname; }
            set { listname = value; }
        }
       
        public GetListFieldInfo()
        {
            this.ExportMode = WebPartExportMode.All;
            listname = default_listname;
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            SPWeb web = SPContext.Current.Web;
            if (web != null)
            {
                try
                {
                    SPList list = web.Lists[ListName];
                    if (list != null)
                    {
                        writer.Write("<h2>" + list.Title + "</h2>");
                        writer.Write("<p><strong>Location: </strong>" + list.DefaultViewUrl + "</p>");
                        writer.Write("<table border=\"0\" cellspacing=\"2\" cellpadding=\"2\" style=\"width: 100%;\">");
                        writer.Write("<tr><td><strong>FIELD NAME</strong></td><td><strong>INTERNAL FIELD NAME</strong></td><td><strong>DATA TYPE</strong></td><td><strong>IS REQUIRED</strong></td><td><strong>IS INDEXED</strong></td></tr>");
                        SPFieldCollection fc = list.Fields;
                        foreach (SPField field in fc)
                        {
                            writer.Write("<tr><td>" + field.Title + "</td><td>" + field.InternalName + "</td><td>" + field.TypeAsString + "</td><td>" + field.Required + "</td><td>" + field.Indexed + "</td></tr>");
                        }
                        writer.Write("</table>");
                    }
                }
                catch (Exception x)
                {
                    writer.Write("Error retrieving list information: " + x.Message);
                }
            }
        }
    }

Comments

No Comments
Powered by Community Server (Commercial Edition), by Telligent Systems