Tuesday, January 26, 2010

Create PDF in .Net

Seems like there is an easy way to create PDF-files with the ise of iTextSharp, came across it here. http://techdotnets.blogspot.com/

Datagrid Export, troublesome templatecolumn

Ran into a problem today, which had me puzzled for couple of hours.

I have a Datagrid to which I add TemplateColumns dynamicly. Works like a charm until the customer wanted to export all the data.

So I happily assumed that al I had to do was:

System.IO.StringWriter sw= new System.IO.StringWriter
HtmlTextWriter writer = new HtmlTextWriter(sw);

dg.RenderControl(writer)

Response.write(sw.ToString());
Response.End();

Works very well as long as the columns are bound. Hower the TemplateColumns are completely blank. I couldn´t figure it out so I did a little googling and came across this blog: http://www.c-sharpcorner.com/uploadfile/dipalchoksi/exportaspnetdatagridtoexcel11222005041447am/exportaspnetdatagridtoexcel.aspx

Just pass your datagrid to this method and it transforms the TemplateColumn (and others) to a Literalcontrol with a text property, and tada..... The vaules appear in the export.

private void ClearControls(Control control)
{
for (int i=control.Controls.Count -1; i>=0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal =
new LiteralControl();
control.Parent.Controls.Add(literal);
try
{literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control,null);
}
catch
{
}
control.Parent.Controls.Remove(control);
}
else
if
(control.GetType().GetProperty("Text") != null)
{
LiteralControl literal =
new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text = (
string)control.GetType().GetProperty("Text").GetValue(control,null);
control.Parent.Controls.Remove(control);
}
}
return;
}