How to add columns to list view programmatically using SharePoint server object model

In this SharePoint 2016 tutorial, We will discuss how to add columns to view programmatically in SharePoint. We will see how to add columns to the SharePoint list view programmatically using SharePoint 2016 server object model in SharePoint 2013/2016 list or document library in Visual Studio 2017.

In this below example, I have a SharePoint 2016 Document Library. This SharePoint 2016 Document Library has two different data types of columns. Those columns are:

  • DocumentLocation (Single line of text):
    This column is a Single line of text.
  • DocumentLanguage (Choice): This column is a Choice field. This language field column has some choice values as:
    • English
    • Hindi
    • Kannad
  • DocumentDepartment (Choice):
    This column is also a Choice field. This department field column has some choice values as: 
    • IT
    • HR
    • Finance

By default, these columns will not appear in the list view in the SharePoint 2016 Document Library or list, So we have to display programmatically using Server object model code (C#) in Visual Studio 2017.

If you are new to SharePoint server side development and visual web part check out the below SharePoint 2016 tutorials:

Add Columns to SharePoint List View programmatically

Below SharePoint 2016 server object model code to display a SharePoint 2016 List/Library Column in View programmatically.

Here I have a button and on the button click I am adding the columns to the SharePoint document library or list.

        public void AddListColumnsToView()
        {
            try
            {
                                
	SPWeb web = SPContext.Current.Web;

                web.AllowUnsafeUpdates = true;
                SPList spList = web.Lists.TryGetList("My List Name");

                /* display a column in view */
                SPView defaultView = spList.DefaultView;
                defaultView.ViewFields.Add("DocumentLocation");
                defaultView.ViewFields.Add("DocumentLanguage");
                defaultView.ViewFields.Add("DocumentDepartment");
                defaultView.Update();

                spList.Update();
                web.AllowUnsafeUpdates = false;
            }
            catch (Exception exc)
            {                
            }            
        }

In the below screenshot, you can see that there will be available one single line of the text column and other choice columns as a view.

Display column as view programmatically in SharePoint
Display column as view programmatically in SharePoint

You may like following SharePoint server object model tutorials:

This SharePoint 2016 tutorial, we discussed how to add a SharePoint List/Library column in the list view programmatically c#.net using SharePoint 2016/2013 server object model code.

>