Monday, August 2, 2010

Gridview to Excel.

Senerio: A gridview hold a data and on a button click we are sending it to Excel letting user to open or save the file. I used this in one of our Sharepoint Webpart.

Assumption: Paging and sorting are enabled. gv is a asp gridview .

protected override void OnPreRender(EventArgs e)
{
gv.AllowPaging = false;
gv.AllowSorting = false;
gv.DataBind();


HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.Charset = "";
this.EnableViewState = false;
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
HtmlForm frm = new HtmlForm();
this.Controls.Add(frm);
frm.Controls.Add(gv);
frm.RenderControl(oHtmlTextWriter);
HttpContext.Current.Response.Write(oStringWriter.ToString());
HttpContext.Current.Response.End();

gv.AllowPaging = true;
gv.AllowSorting = true;
gv.DataBind();

}


Hope it helps and Thank you for Visiting!

Thursday, July 22, 2010

Next to Follow:

Next :
  • Sharepoint Twitter Webpart.
  • Rotating News Banner Webpart

Copy a file of Document Library along with its metadata.

The straight forward way to copy a document from document library is to use CopyTo function like:
ListItem.CopyTo(distinationURL+"/"+ListItem.File.Name);
This function will copy the file to distinationURL along with its metadata. But if anyone of the field is a lookup field, then it will not copy any of the meta data. For this purpose you must Copy the file and update its metadata seperately. I have used as following in one of my event handler.

SPFile sourceFile=properties.ListItem.File;
SPFile destFile;
using(Stream stream=soureceFile.OpenBinaryStream())
{
destFile=properties.ListItem.Web.Lists[properties.ListTitle].RootFolder.Files.Add(distinationURL,stream,true);
}

SPListItem destinationListItem=destFile.Item;
//Then start copying the metadata as following
destinationListItem["Title"]=properties.ListItem["Title"];
destinationListItem["abc"]=properties.ListItem["abc"];
//copying lookupfield
string partsOfField=properties.ListItem["lookupField"].ToString().Split(';');
destinationListItem["lookupField"]=new SPFieldLookupValue(int.Parse(partsOfField[0].ToString()), partsOfField[1].ToString());

destinationListItem.Update();


Hope it helps!

Welcome Note

I am trying to share some Sharepoint Object model concepts and examples here. Hope it helps to spread my ideas around.