Thursday, March 8, 2012

EMail your Datagrid SharePoint 2010

Hello all,

In this post we will discuss the shortest way to send the Results of a data grid in the content of E-Mail with its HTML.

Our Game Plan:
1- Do your logic Bind the Data grid get the result.
2- Extract the HTML of the data grid.
3- Build the XSL fro your Mail formattting.
4- Send the mail.

I'll skip step 1 as it is very easy and you will find it all over the Internet.

Assuming we have our Data grid binded noe we need to extract thos results as HTML how we will do that by,
this Method
private string GetGridHTML()
            StringBuilder SB = new StringBuilder();
            StringWriter SW = new StringWriter(SB);
            HtmlTextWriter htmlTW = new HtmlTextWriter(SW);


            string dataGridHTML = SB.ToString();

            //dataGridHTML = Server.HtmlEncode(dataGridHTML);

            return dataGridHTML;

this code will give exception GridView must be placed inside a form tag with runat=“server” even after the GridView is within a form tag

You are calling GridView.RenderControl(htmlTextWriter), hence the page raises an exception that a Server-Control was rendered outside of a Form.
You could avoid this execption by overriding VerifyRenderingInServerForm

public override void VerifyRenderingInServerForm(Control control)
  /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
     server control at run time. */
Ok now we have our Data grid content HTML .