How to transfer asp.net grid view data in HTML table - asp.net

I am working in asp.net and in that i am using grid view and now i want to convert grid view data which is dynamic to the html table so i can send an email. if any one know it please tell me.
Thank You

You can use
using System.IO;
using System.Text;
using System.Net.Mail;
private string GridViewToHtml(GridView gv)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.RenderControl(hw);
return sb.ToString();
}
protected void SendMailButton_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.Body = GridViewToHtml(GridView1);
mail.IsBodyHtml = true;
// The same logic as you use for sending mail
}
public override void VerifyRenderingInServerForm(Control control)
{
}

The Kettic GridView control can easily export the data in GridView to HTML and create an html format file to viewing in a web browser or MS Word.

Related

Export Gridview Data to Excel in ASP.NET Linq data bind

I am using bellow code for export gridview data to excel but problem is that whole page export to excel. I want only gridview data not whole page export. How can solve this problem?
HtmlForm form = new HtmlForm();
Response.Clear();
Response.Buffer = true;
string filename = "GridViewExport_" + DateTime.Now.ToString() + ".xls";
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gdvInBox.AllowPaging = false;
gdvInBox.DataBind();
form.Controls.Add(gdvInBox);
this.Controls.Add(form);
form.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
Thanks in Advance.
It's pretty easy to set up the excel export that will export only the gridview. This has been tested and will only export the gridview that appears on your given web page.
For your C# code use the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class vxcel_export : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=file-name.xls");
Response.ContentType = "application/vnd.xlsx";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
}
In your aspx code use the following:
Make sure you add EnableEventValidation="false" to the <%#Page %> code at the top of the page.
Place the following code where you want to put the button to export your gridview to Excel:
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Whatever you want your button to say" />
You can modify the Height and Width to whatever size you want in the button.
That's it. One thing to keep in mind is that when you export the file it's not a true excel file until you save it as a workbook/Excel File.
I had to also apply the following code to my page to get this to work.
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
I found the solution here --> GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Displaying a web page as a pdf with click of a button

I have a new requirement to have a button in my web page, and upon clicking, it displays the web page as a PDF. On researching I found that iTextSharp is used for such purpose.
But I have many Telerik and ASP controls in my web page too. Can I get that also in the PDF using iTextSharp?
If yes then can anyone please provide me a basic link to start using iTextSharp as I haven't came across this tool yet.
According to the answer from #ahaliav I tried with the following code. However, I'm not getting the controls on the pdf.
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(HtmlContent);
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
HTMLWorker worker = new HTMLWorker(document);
// step 2:
// we create a writer that listens to the document
// and directs a XML-stream to a file
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
// step 3: we create a worker parse the document
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(reader);
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
//Response.Write(document);
//Response.End();
}
protected override void Render(HtmlTextWriter writer)
{
// setup a TextWriter to capture the markup
TextWriter tw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(tw);
// render the markup into our surrogate TextWriter
base.Render(htw);
// get the captured markup as a string
string pageSource = tw.ToString();
// render the markup into the output stream verbatim
writer.Write(pageSource);
// remove the viewstate field from the captured markup
HtmlContent = Regex.Replace(pageSource,
"<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\".*?\" />",
"", RegexOptions.IgnoreCase);
// the page source, without the viewstate field, is in viewStateRemoved
// do what you like with it
}
Please help .
I have other option also,that is to display the image of the full web page when i click a button.Can anyone guide me to any possible directions for these two issues please.
I finally changed my code as:
Response.ContentType = "application/msword";
Response.AddHeader("content-disposition", "attachment;filename=TestPage.doc");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
MemoryStream msOutput = new MemoryStream();
With this i am able to get the msword document containing all my controls ,but i am also getting some unwanted texts,how can i remove that,if anyone encountered the same problem?
After some research i did not find any solution for showing the controls in the html this code below works fine but with out showing the controls,
in the past i used this http://www.winnovative-software.com/ and it works good for html pages including all controlls you can also test it onlie, the "only" problem is it you need to pay for the license
protected void btnExportToPdf_Click(object sender, EventArgs e)
{
renderPDF = true;
}
protected override void Render(HtmlTextWriter writer)
{
if (renderPDF == true)
{
MemoryStream mem = new MemoryStream();
StreamWriter twr = new StreamWriter(mem);
HtmlTextWriter myWriter = new HtmlTextWriter(twr);
base.Render(myWriter);
myWriter.Flush();
myWriter.Dispose();
StreamReader strmRdr = new StreamReader(mem);
strmRdr.BaseStream.Position = 0;
string pageContent = strmRdr.ReadToEnd();
strmRdr.Dispose();
mem.Dispose();
writer.Write(pageContent);
CreatePDFDocument(pageContent);
}
else
{
StringBuilder sb = new StringBuilder();
HtmlTextWriter tw = new HtmlTextWriter(new System.IO.StringWriter(sb));
base.Render(tw);
// get the captured markup as a string
string pageSource = tw.ToString();
//Get the rendered content
string sContent = sb.ToString();
//Now output it to the page, if you want
writer.Write(sContent);
}
}
public void CreatePDFDocument(string strHtml)
{
string strHTMLpath = Server.MapPath("MyHTML.html");
StreamWriter strWriter = new StreamWriter(strHTMLpath, false, Encoding.UTF8);
strWriter.Write(strHtml);
strWriter.Close();
string strFileName = HttpContext.Current.Server.MapPath("map1.pdf"); // strFileName "C:\\Inetpub\\wwwroot\\Test\\map1.pdf"
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
StringReader se = new StringReader(strHtml);
TextReader tr = new StreamReader(Server.MapPath("MyHTML.html"));
//add the collection to the document
document.Open();
/////////
iTextSharp.text.html.simpleparser.HTMLWorker worker = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
worker.StartDocument();
//// step 5: parse the html into the document
worker.Parse(tr);
//// step 6: close the document and the worker
worker.EndDocument();
//worker.Parse(tr); // getting error "Illegal characters in path"
document.Close();
ShowPdf(strFileName);
}
public void ShowPdf(string strFileName)
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
Response.ContentType = "application/pdf";
Response.WriteFile(strFileName);
Response.Flush();
Response.Clear();
}
A very simple Google search brings us to the following forum thread which has your "sollution":
http://forums.asp.net/t/1039486.aspx/1
iTextSharp comes with a little companion : XML Worker
For a demo, have a look here
Even though the documentation refers to the Java API, the adaptation to C# should be straightforward.
As for Telerik/ASP tags, you can extend XMLWorker and define how to convert such tags into PDF elements.

How can i write a datatable content on web page in XMl foramte in asp.net?

How can i write a datatable content on web page in XMl foramte in asp.net?
i also need to customize the datatable before writing to web page.
Edited:-
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/xml";
DataTable dt = new DataTable("XML");
String email = EmailAddress.Text.ToString();
dt.Load(obj.GetXML("XYZ#gmail.com"));
//now i want this dt to dosplayed in the XMl form on the same page, how can i achieve this?
'XmlDocument xml = new XmlDocument();
'XmlTextReader xr=new XmlTextReader(
'WriteGoogleMap(dt.ToString(), Response.OutputStream);
'Response.End();
//System.Xml.
}
Try this :
public string GetXml(string urlBase)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = true;
StringBuilder output = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(output, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
// Repeat this code:
writer.WriteStartElement("url");
writer.WriteElementString("loc", "[your url]");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
}
return output.ToString();
}
Then use the result to feed a label :
<script runat="server" type=text/C#>
protected void Page_Load(object sender, EventArgs e)
{
myLabel.Text = HttpUtility.HtmlEncode(
GetXml("http://www.dotnetperls.com/")
);
}
</script>
[Edit]
I think you should start by the beginning. Do not mix all concepts in your single question. Spend time for learning the basics (read books, take courses, etc.). In your specific case, I suggest you to split the work in several layers:
A data layer the is responsible to build a datatable
A business or service layer, capable of creating the xml document from the databable
A presentation layer that will contains :
a custom http handler (.ashx) that will return the xml
a visual page that can show the html representation of the Xml
good luck
DataTable has method named:
WriteXml

Convert Datagrid or Gridview to excel with Page break

I need to convert either an ASP.NET Datagrid or GridView to excel with a page-break that can be part of the target excel.
The first part to convert the grid control to excel is not that complex and fairly easy to do, but my problem is how to insert a page break to the excel file during the conversion process.
Thanks for the help.
Here is the complete code to Export GridView to Excel:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class ExportGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = BindData();
GridView1.DataBind();
}
}
private string ConnectionString
{
get { return #"Server=localhost;Database=Northwind;
Trusted_Connection=true"; }
}
private DataSet BindData()
{
// make the query
string query = "SELECT * FROM Categories";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
return ds;
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;
filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving than
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for the
specified ASP.NET server control at run time.
}
}

Render a user control ascx

I want to use an ascx as a template, and render it programatically, using the resulting html as the return value of an ajax method.
Page pageHolder = new Page();
MyUserControl ctlRender = (MyUserControl)pageHolder.LoadControl(typeof(MyUserControl),null);
pageHolder.Controls.Add(ctlRender);
System.IO.StringWriter swOutput = new System.IO.StringWriter();
HttpContext.Current.Server.Execute(pageHolder, swOutput, false);
return swOutput.ToString();
This all executes, and the Page Load event of the user control fires, but the StringWriter is always empty. I've seen similar code to this in other examples, what am I missing?
Have you tried this:
public string RenderControl(Control ctrl)
{
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctrl.RenderControl(hw);
return sb.ToString();
}
Taken directly from the article here:
ASP.NET Tip: Render Control into HTML String
You always have to use something like this.Controls.Add(TemplateControl.LoadControl("~/PathTo/YourControl.ascx")
The reason is, that there is no internal mapping of Types to there ascx-file (only the other way arround). So this means if you initialize new YourControl(), it will not do anything you defined in the ascx part. If you would have
protected override void protected override void Render(HtmlTextWriter output) {
output.WriteLine("Test");
}
this would give you "Test" in the place you rendered your control to.

Resources