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"];
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:
- SharePoint create folder programmatically using CSOM
- Get SharePoint List Name and GUID using PowerShell and CSOM
- Get all lists and document libraries programmatically using CSOM in SharePoint Online
After working for more than 15 years in Microsoft technologies like SharePoint, Office 365, and Power Platform (Power Apps, Power Automate, and Power BI), I thought will share my SharePoint expertise knowledge with the world. Our audiences are from the United States, Canada, the United Kingdom, Australia, New Zealand, etc. For my expertise knowledge and SharePoint tutorials, Microsoft has been awarded a Microsoft SharePoint MVP (9 times). I have also worked in companies like HP, TCS, KPIT, etc.