use button from masterpage - c#

I am Creating a web app in which i have a master page with 5 other page
welcome
user
employee
admin
company
Every page have a gridview (i.e I have 5 gridviews) gridview contain different data for different page
and i used this to export the gridview data into excel
protected void imgexcel_Click(object sender, ImageClickEventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
row.BackColor = System.Drawing.Color.White;
row.Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
this is my normal coding for export
but i want to add button on my masterpage and exporting of data depends on which page is user using (if the user is on welcome page data of welcome page must be exported on button click and if he is on user page and click on button click the data of user must be exported and so on)

string s = this.Page.Request.FilePath; // "/Welcome.aspx"
You can use this code for holding the page name in a string so you can use this string in a switch-case structure (in button OnClick).
switch(string)
{
case:"welcome": //...
case:"user": //...
case:"employee": //...
}
Hope it helps.

You can use FindControl to find the GridView on every page. You just have to make sure they all have the same ID.
protected void Button1_Click(object sender, EventArgs e)
{
//first find the ContentPlaceHolder control
ContentPlaceHolder contentPlaceHolder = FindControl("ContentPlaceHolder1") as ContentPlaceHolder;
//then find the GridView control inside the ContentPlaceHolder
GridView gridview = contentPlaceHolder.FindControl("GridView1") as GridView;
//or the same as above but in a single line of code
GridView gridview = FindControl("ContentPlaceHolder1").FindControl("GridView1") as GridView;
//do stuff with the GridView
gridview.Visible = false;
}

Related

Asp.Net - Export two Gridviews to excel or pdf

I have a page that shows two grids side by side; "Expenses" and "Income".
I want the user to be able to export it to excel or pdf or print it as it's shown on the web page, side by side.
How can I do it?
What's the best practice?
Thanks.
Probably Reporting Services (SSRS)
but in case sql server
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
// Re-Bind data to GridView
using (CompMSEntities1 CompObj = new CompMSEntities1())
{
Start = Convert.ToDateTime(txtStart.Text);
End = Convert.ToDateTime(txtEnd.Text);
GridViewSummaryReportCategory.DataSource = CompObj.SP_Category_Summary(Start, End);
SP_Category_Summary_Result obj1 = new SP_Category_Summary_Result();
GridView1.DataBind();
GridView1.Visible = true;
ExportTable.Visible = true;
}
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.Style.Add(" font-size", "10px");
//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GGridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[4].Style.Add("background-color", "green");
for (int i = 1; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
// row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
row.Cells[3].Style.Add("background-color", "#C2D69B");
row.Cells[4].Style.Add("background-color", "#C2D69B");
}
}
GridView1.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();
}
For printing you can specify special styles using #media print { } block in CSS and initiate printing in browser manually or by calling window.print() in JavaScript.
For export to Excel you can use, for example, http://closedxml.codeplex.com/.
For export to PDF you can use, for example, http://sourceforge.net/projects/itextsharp/.
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
if (RadioButtonList1.SelectedIndex == 0)
{
GridView1.ShowHeader = true;
GridView1.GridLines = GridLines.Both;
GridView1.AllowPaging = false;
GridView1.DataBind();
}
else
{
GridView1.ShowHeader = true;
GridView1.GridLines = GridLines.Both;
GridView1.PagerSettings.Visible = false;
GridView1.DataBind();
}
ChangeControlsToValue(GridView1);
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=GridViewToExcel.xls");
Response.ContentType = "application/excel";
StringWriter sWriter = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
HtmlForm hForm = new HtmlForm();
GridView1.Parent.Controls.Add(hForm);
hForm.Attributes["runat"] = "server";
hForm.Controls.Add(GridView1);
hForm.RenderControl(hTextWriter);
// Write below code to add cell border to empty cells in Excel file
// If we don't add this line then empty cells will be shown as blank white space
StringBuilder sBuilder = new StringBuilder();
sBuilder.Append("<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"> <head><meta http-equiv="Content-Type" content="text/html;charset=windows-1252"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>ExportToExcel</x:Name><x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head> <body>");
sBuilder.Append(sWriter + "</body></html>");
Response.Write(sBuilder.ToString());
Response.End();
}

ASP Table to Excel

When viewing ASPX in website, I got a table with few text in the cells, e.g.:
tab.Rows[1].Cells[1].innerHtml = "Booked :"
(In a lot of rows and cells but with different text in each cell)
Now I just want to click a button, and data in the table will be downloaded into an Excel file.
Table ID : tab
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Table tbl = new Table();
TableRow tr = new TableRow();
TableCell tcel = new TableCell();
tcel.Text = "id";
tr.Cells.Add(tcel);
TableCell tcel1 = new TableCell();
tcel1.Text = "id1";
tr.Cells.Add(tcel1);
tab.Rows.Add(tr);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string filename = "ExportExcel.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
//DataGrid dgGrid = new DataGrid();
//dgGrid.DataSource = tbl;
//dgGrid.DataBind();
//Get the HTML for the control.
tab.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
Modified with watraplion answer, but still not answer..
Error at:
DataTable dt = dt; //Use of unassigned local variable 'dt'
Try this :
aspx Design View :
<body>
<form id="form1" runat="server">
<div>
<asp:Table ID="Table1" runat="server">
</asp:Table>
</div>
<div>
<asp:Button ID="btnExport" onclick="btnExport_Click" Text="Export" runat="server">
</div>
</form>
</body>
aspx.cs ( code behind )
protected void Page_Load(object sender, EventArgs e)
{
TableRow tr = new TableRow();
TableCell tcel = new TableCell();
tcel.Text = "id";
tr.Cells.Add(tcel);
TableCell tcel1 = new TableCell();
tcel1.Text = "id1";
tr.Cells.Add(tcel1);
Table1.Rows.Add(tr);
}
protected void btn_Click(object sender, EventArgs e)
{
string filename = "ExportExcel.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
//Get the HTML for the control.
Table1.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
First to say that this what you are trying to do is not export to excel, but you send a html with a wrong headers to trick browser to open this content with excel.
This solution has many problems, excel it self will warn user that content is different from extension, because you send html and your response headers are saying that this is a excel file. And I can bet that some antimalware software on client or something similar on server, will block this response since serving different content than declared in headers is known malware behavior.
It's far more better and easier to use dedicated excel library, for example EPPlus, look here for ASP.NET ashx handler that exports DataTable to real excel file :
https://stackoverflow.com/a/9569827/351383

Append information to Excel file on GridView Export in ASP.NET C#

I'm exporting a GridView to Excel with the following code:
protected void export_OnClick(object sender, EventArgs e)
{
string style = #"<style> .text { mso-number-format:\#; } </style> ";
// Let's hide all unwanted stuffing
GridView1.AllowPaging = false;
GridView1.AllowSorting = false;
// Let's bind data to GridView
BindGrid();
//Change the color back to white
GridView1.HeaderRow.Style.Add("background-color", "#ffffff");
//Apply color to the header
for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
{
GridView1.HeaderRow.Cells[i].Style.Add("background-color", "#e0e0e0");
}
// Let's output the Gridview
Response.Clear();
Response.ContentType = "application/vnd.xls";
Response.AddHeader("content-disposition", "attachment;filename=" + reportid + ".xls");
StringWriter swriter = new StringWriter();
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
GridView1.RenderControl(hwriter);
Response.Write(style);
Response.Write(swriter.ToString());
Response.End();
}
Now I need to append a Name on the first row, Date & Time on the second row and possibly some other information on the third row. I will also like to leave a row between the actually GridView data and this information. Is this possible? If so, would you be so kind and provide some examples on how can I accomplish this. Thank you.
Just go ahead and add it. Add a carriage return after each to make Excel advance to the next row (use tabs to advance to the next cell).
Response.Write(style);
Response.Write("Pretty Excel Export File\n");
Response.Write("Generated on " + DateTime.Now.ToShortDateString() + "\n\n");
Response.Write(swriter.ToString());
Response.End();

Exporting GridView to XLS --- Paging Issue

I have a GridView and I intend to export it into .xls file. Paging is enabled in this gridview. The codes I am currently using can only export the first page of the gridview.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition","attachment;filename=DataTable.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
//As you notice, below I tried to disable the paging yet it's unsuccessful
//FYI I am able to really prevent first column, header row, and footer row to
//be exported through this
gvGridView.Columns[0].Visible = false;
gvGridView.HeaderRow.Visible = false;
gvGridView.FooterRow.Visible = false;
gvGridView.AllowPaging = false;
for (int i = 0; i < gvGridView.Rows.Count; i++)
{
gvGridView.Rows[i].Attributes.Add("class", "textmode");
}
gvGridView.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
I noticed this question was previously asked yet there was no correct answer.
Any help is appreciated.
Thank's
You should rebind your GridView after you specify gvGridView.AllowPaging = false;, then export. Otherwise .RenderControl(hw); will only be rendering the currently selected GridView page.
Just make a GridView.DataBind() after change the AllowPaging property.

Column Values Customisation- Export Excel in ASP.NET

I have to export gridview in to the excel sheet 2003. With my code I can Export the data into eXcel Sheet directly. But If there is a null value for the column, Then how do I replace with empty string in Excel sheet. There is a date column which is null, is there any event handler that occurs between export button click and the loading the data into excel. If there is one I can compare the values in the database and can replace the null value with empty String. in the evnt handler.
Please point me in right direction.
Thank you
On click of the export button, you can iterate through your grid rows and replace whatever you need. For example, the code below will replace : with .:
protected void btnExport_Click(object sender, EventArgs e)
{
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
string attachment = "attachment; filename=SummaryReport" + DateTime.Now.ToString() + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
foreach (GridViewRow grdRow in grdProjectTasks.Rows)
{
Label lblActualDuration = (Label)grdRow.FindControl("lblActualDuration");
lblActualDuration.Text = lblActualDuration.Text.Replace(":", ".");
}
grdProjectTasks.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

Categories

Resources