1

How we can create a SharePoint List from Data-table.

6
0

This might be a little tricky if you have different datatypes in your datatable.

But an example, using only text fields could be something like this.

/* Create datatable */
      DataTable dt = new DataTable();
      dt.Columns.Add("Test1");
      dt.Columns.Add("Tets2");

      using (SPSite site = new SPSite("http://myurl"))
      {
        using (SPWeb web = site.OpenWeb())
        {
          SPList newList = null;

          try
          {
            Guid newListGuid = web.Lists.Add("TempList", "This is my temp list, it will be removed when used", SPListTemplateType.GenericList);
            newList = web.Lists[newListGuid];

            if (newList != null)
            {
              /* Loop through the datatable and add columns to the list */
              foreach (DataColumn dc in dt.Columns)
              {
                newList.Fields.Add(dc.ColumnName, SPFieldType.Text, false);
              }

              /* Update the list to get the new fields */
              newList.Update();

              /* Populate the list from the datatable */
              SPListItem newItem = null;
              foreach (DataRow row in dt.Rows)
              {
                /* Create a new item in the list */
                newItem = newList.AddItem();

                foreach (DataColumn dc in dt.Columns)
                {
                  newItem[dc.ColumnName] = row[dc].ToString();
                }

                /* Save the item to the list */
                newItem.Update();
              }
            }
          }
          catch
          {
            /* Do some logging */
          }
          finally
          {
            if (newList != null)
            {
              newList.Delete();
            }
          }
        }
      }

Source: http://social.technet.microsoft.com/Forums/en-US/93ac2dca-9ac4-41d2-9349-21fb068619bf/how-to-convert-a-datatable-to-splist?forum=sharepointdevelopmentprevious

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.