To Serialize a datatable we can use the inbuilt function WriteXml. We have put in 3 parameters the filename,xmlwritemode,writehierarchy.

Giving a name to the datatable is a must or you might get an exception “Cannot serialize the DataTable. DataTable name is not set”. In this case we have used the name “dtDoctype” using  the TableName  property  of  datatable.

If you forget to mention the writemode, you might get other errors like “Root element is missing.” While trying to de-serialize it.

The parameter “Mode” is to identify if it is a new entry or an edit. The parameter “item” indicates which list the item is being fetched from.

String docxmlPath = @”C:\KMUserControl\docList.xml”;

if (!File.Exists(docxmlPath))

{

   DataTable dt = new DataTable();

               

   dt = adBuzLogic.PopulateInformationTypeDataTable(ref Mode, item);

   dt.TableName = “dtDocType”;

   dt.WriteXml(docxmlPath, XmlWriteMode.WriteSchema, true);

 

   ddlInfoType.DataSource = dt;

   ddlInfoType.DataBind();

   if (Mode.Equals(“Edit”))

   {

     if (item != null)

     {

 

     ddlInfoType.Items.FindByText(item.ParentList.Title).Selected = true;

       }

    }

 

}

else

{

 

   DataTable dt = new DataTable();

   dt.ReadXml(docxmlPath);

               

   ddlInfoType.DataSource = dt;

   ddlInfoType.DataTextField = dt.Columns[0].ToString();

   ddlInfoType.DataValueField = dt.Columns[0].ToString();

   ddlInfoType.DataBind();

   if (Mode.Equals(“Edit”))

   {

     if (item != null)

     {

 

     ddlInfoType.Items.FindByText(item.ParentList.Title).Selected = true;

       }

    }

}

 

In PopulateInformationTypeDataTable function, we simply return a datatable from items in a Sharepoint list. ———————-

public DataTable PopulateInformationTypeDataTable(ref string mode, SPListItem editItem)

{

    DataTable dt = new DataTable(); //Define a datatable.

    DataColumn column = new DataColumn(); //Define a datacolumn.Here only one column is added which is of type string.

    column.DataType = Type.GetType(“System.String”);

    column.ColumnName = “item”;

    dt.Columns.Add(column);

try

{

SPWeb ospWeb = SPContext.Current.Web;

foreach (SPList ospList in ospWeb.Lists)

{

if (((ospList.BaseTemplate == SPListTemplateType.DocumentLibrary) || (ospList.BaseTemplate == SPListTemplateType.PictureLibrary)) && (ospList.ContentTypes[“New Document”] != null)) //filter condition,from where to read items to form a datatable.

 {

    DataRow dr = dt.NewRow(); //dynamically adding datarows by reading from Sharepoint lists.

    ListItem liInformationType = new ListItem(ospList.Title, ospList.RootFolder.Name);

     dr[0] = liInformationType; //assigning value to the datarow.

     dt.Rows.Add(dr[0]); //adding datarow to datatable.

    }

  }

}

 catch (Exception exception)

 {

      Throw exception;         

 

  }

  return dt;

}

Advertisements