Share via


SharePoint : How to Hide Columns in List Forms without using SharePoint Designer

Recently a requirement was posted to me where the end users were

On successful completion, it will show a message that the execution is completed.

need to hide columns in list forms without using SharePoint designer. Our site admins can do this easily using SharePoint designer but since there were many lists and requests so it was not possible to go to each and everyone and carry out this task manually. Hence I created a tool using C#. This works in both MOSS 2007 and SPS 2010.

This takes three inputs:

  1. 1. The complete List URL. ex: http://webApplication/Site/Lists/ListName/Allitems.aspx. (Note:- The URL to any view can be used here).
  2. 2. The field name that is to be hidden.
  3. 3. 1, 2 or 3 based on the requirement as these numbers stands for "1 for EditForm, 2 for DisForm and 3 for NewForm".

Here is the code to do this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
 
namespace HideFieldInListFormRahul
{
 class Program
 {
 static void  Main(string[] args)
 {
 try
 {
 Console.WriteLine("This tool will hide a field from list forms. It requires List Url and field URL");
 Console.WriteLine("Please enter list URL");
 String listUrl = Console.ReadLine();
 Console.WriteLine("Please enter column name");
 String columnName = Console.ReadLine();
 Console.WriteLine("Enter 1 for EditForm, 2 for DisForm and 3 for NewForm");
 String formType = Console.ReadLine();
 using (SPSite site = new SPSite(listUrl))
 {
 using (SPWeb web = site.OpenWeb())
 {
 String listRel = listUrl.Substring(web.Url.Length);
                        SPList list = web.GetListFromUrl(listUrl);
 SPField field = list.Fields[columnName];
 if (formType.Trim().Equals("1"))
 {
 field.ShowInEditForm = false;
 
 }
 else if  (formType.Trim().Equals("2"))
 {
 field.ShowInDisplayForm = false;
 }
 else if  (formType.Trim().Equals("3"))
 {
 field.ShowInNewForm = false;
 }
 else
 {
 Exception ex = new  Exception("No Proper number between 1 to 3 has been entered");
 throw ex;
 }
 field.Update();
 Console.WriteLine("The execution completed.Press Enter to Exit");
 Console.ReadLine();
 }
 }
 
 }
 
 catch (Exception e)
 {
 Console.WriteLine(e.Message);
 Console.WriteLine(e.StackTrace);
 Console.ReadLine();
 }
 }
 }
}