To show SharePoint list items in a grid or any repeater control then you would have got the data into a DataTable object. Recently I observed that SharePoint object model has a method to get all the list items into a DataTable i.e.

    DataTable tempTbl = spList.GetItems(query).GetDataTable();

but unfortunately the above data table will not have the attachments information. Here is a workaround for getting even the attachment information into the data table.

Get all the data into the data table using the above code and then add a new column to store the attachment information. Also bind a hidden field of the repeater to the ID value of the data table.

    DataTable tempTbl = spList.GetItems(query).GetDataTable();
    tempTbl.Columns.Add("AttachmentsInfo");
    grdCDDocInfo.DataSource = tempTbl;
    grdCDDocInfo.DataBind();

In row data bound of the control update the new attachment information column. Find the code below to get attachments information.

    void grdCDDocInfo_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       if (e.Row.RowType == DataControlRowType.DataRow)
       {
          if (!String.IsNullOrEmpty(hdnCompanyID.Value))
          {
              SPList spList = oWeb.Lists.TryGetList("List Name");
              SPListItem item = spList.GetItemById(Convert.ToInt32((e.Row.FindControl("itemID") as HiddenField).Value));

              string attachmentInfo = String.Empty;
              foreach (string filename in item.Attachments)
              {
                  attachmentInfo += item.Attachments.UrlPrefix + filename + " " + filename
                  (e.Row.FindControl("ltAttachmentsInfo") as Literal).Text = attachmentInfo;
              }
          }
       }
   }

This will display all the list items in a grid with the attachments of the items.

Happy Coding 🙂

Advertisements