[Solved] Cannot set Column ‘ID’ to be null. Please use DBNull instead in SharePoint Online

In this SharePoint csom example, I will explain how to solve the error “Cannot set Column ‘ID’ to be null. Please use DBNull instead” which comes while working with client-side object model (csom C#.Net) in SharePoint Online Office 365.

I have written some code to retrieve all the SharePoint list templates and bind the SharePoint list template to a dropdown list, and I got the error “Cannot set Column ‘ID’ to be null. Please use DBNull instead”. I have retrieved all the list templates and stored to a data table and bound the list template to the dropdown list. I am trying to run the below code and got the error.

Web web = clientContext.Web;
ListTemplateCollection templateColl = web.ListTemplates;
clientContext.Load(templateColl);
clientContext.ExecuteQuery();

DataTable dt = new DataTable();
dt.Columns.Add(“ID”, typeof(Int32));
dt.Columns.Add(“Title”, typeof(string));

foreach (ListTemplate template in templateColl)
{
DataRow dr = dt.NewRow();
dr[“ID”] = template[“ID”];
dr[“Title”] = template.Name;
dt.Rows.Add(dr);
}

Once I run the above code, it gave me the below error in the below line.

dr["ID"] = template["ID"];
.net cannot set column to be null. please use dbnull instead
.net cannot set column to be null. please use dbnull instead

Solution to error ‘Cannot set Column ‘ID’ to be null. Please use DBNull instead’:

Here the error is coming because I have set the ID value as integer “dt.Columns.Add(“ID”, typeof(Int32));”.

dr[“ID”] = template[“ID”]; //But template[“ID”] returns null. So I have got the error Cannot set Column ‘ID’ to be null. Please use DBNull instead”.

So I have added “ListTemplateTypeKind” property whose return type is “integer”

dr[“ID”] = template.ListTemplateTypeKind;

In the above SharePoint article, we discussed how to resolve the error “Cannot set Column ‘ID’ to be null. Please use DBNull instead” while binding the SharePoint list template to the dropdown list in SharePoint online.

You may like the following tutorials:

>