Issue of addition of blank row in gridview - c#

I have fetched data from db table, bound it to gridview and then export data from gridview to excel. It works fine.
But when I added a row at the top of gridview in databound event by using below code:
protected void gvReports_DataBound(object sender, EventArgs e)
{
if (gvReports.Rows.Count > 0)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
int count = gvReports.HeaderRow.Cells.Count;
TableHeaderCell cell = new TableHeaderCell();
cell.BorderWidth = 0;
cell.Text = "Commodity " + ddlCommMFArrival.SelectedItem.Text;
cell.ColumnSpan = count - 2;
row.Controls.Add(cell);
row.BackColor = ColorTranslator.FromHtml("#f5fafd");
gvReports.HeaderRow.Parent.Controls.AddAt(0, row);
}
}
Code to export Gridview to Excel:
protected void btnExport_Click(object sender, EventArgs e)
{
for (int i = 0; i < gvReports.Rows.Count; i++)
{
for (int j = 0; j < gvReports.Rows[i].Cells.Count; j++)
{
if (gvReports.Rows[i].Cells[j].Text == "NA")
{
gvReports.Rows[i].Cells[j].HorizontalAlign = HorizontalAlign.Right;
}
}
}
gvReports.HeaderRow.Cells[1].Visible = false;
gvReports.HeaderRow.Cells[2].Visible = false;
string filename = string.Empty;
int ddlselect = Convert.ToInt32(ddlCommMFArrival.SelectedValue);
if (ddlselect == 1)
{
filename = "MarketFee" + DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "") + "";
}
else if (ddlselect == 2)
{
filename = "Commodity Arrival" + DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "") + "";
}
//Export gridview data into MS Excel
blExportToExcel blExport = new blExportToExcel();
//Export gridview data into MS Excel
blExport.ExportGridViewToExcel(gvReports, this, filename);
}
public void ExportGridViewToExcel(GridView grv, System.Web.UI.Page pg, string fileName)
{
grv.AllowPaging = false;
pg.Response.Clear();
pg.Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".xls");
pg.Response.Charset = "";
pg.Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
grv.RenderControl(htmlWrite);
pg.Response.Write(stringWrite.ToString());
pg.Response.End();
grv.AllowPaging = true;
}
Then it adds a blank row at position 0 as well as in excel (export data from gridview to excel) and truncates the last row from gridview. Anyone knows what is the issue?

Try moving your HeaderRow addition logic out of DataBound and into RowCreated. Add this to the GridView declaration:
OnRowCreated="gvReports_RowCreated"
And then this is the RowCreated (note the DataControlRowState.Insert):
protected void gvReports_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
int count = e.Row.Cells.Count;
TableHeaderCell cell = new TableHeaderCell();
cell.BorderWidth = 0;
cell.Text = "blah";
cell.ColumnSpan = count - 2;
row.Controls.Add(cell);
row.BackColor = ColorTranslator.FromHtml("#f5fafd");
gvReports.Controls[0].Controls.AddAt(0, row);
}
}

Related

How to Export multiple header Gridview Data to Excel

I have a gridview which has multiple headers added during run time as shown in snap below:
I want to export the data from this gridview to excel for which I have the following code:
protected void Button1_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";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
gdView.HeaderRow.BackColor = Color.White;
foreach (TableCell hcell in gdView.HeaderRow.Cells)
{
hcell.BackColor = Color.White;
}
foreach (GridViewRow row in gdView.Rows)
{
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
cell.CssClass = "textmode";
}
}
}
gdView.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
// controller
}
The excel output I am getting is as follows:
As you can see the color of the header rows is continuing beyond the table area. Also the top header rows are collapsed in the excel output.
Request you all to kindly suggest how this can be resolved.
Thanks.
I could finally solve the issue by modifying the code as below:
protected void Button1_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";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int x = 0; x <= 3; x++)
{
GridViewRow rows = (GridViewRow)gdView.HeaderRow.Parent.Controls[x];
rows.BackColor = Color.White;
rows.Height = 15;
for (int i = 0; i <= rows.Cells.Count - 1; i++)
{
rows.Cells[i].BackColor = Color.Maroon;
}
}
foreach (GridViewRow row in gdView.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
cell.VerticalAlign = VerticalAlign.Middle;
cell.CssClass = "textmode";
}
}
gdView.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
// controller
}

Export nested Gridview to Excel error

I need to export nested Gridview to Excel with the following code that I get from search, but when I click the Export button it raised an error:
An exception of type 'System.ArgumentOutOfRangeException' occurred in
mscorlib.dll but was not handled in user code
This is the code:
protected void ExportExcel(object sender, EventArgs e)
{
DataTable dt = new DataTable("GridView_Data");
GridView grvPayrollDetails = (GridView)grvPayroll.Rows[1].FindControl("grvPayrollDetails");
foreach (TableCell cell in grvPayroll.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (TableCell cell in grvPayrollDetails.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
dt.Columns.RemoveAt(0);
foreach (GridViewRow row in grvPayroll.Rows)
{
GridView grvPayrollDetailscell = (row.FindControl("grvPayrollDetails") as GridView);
for (int j = 0; j < grvPayrollDetailscell.Rows.Count; j++)
{
dt.Rows.Add(row.Cells[1].Text, row.Cells[2].Text, grvPayrollDetailscell.Rows[j].Cells[0].Text, grvPayrollDetailscell.Rows[j].Cells[1].Text);
}
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=grvPayrollDetails.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
grvPayroll is the Master Gridview and Gridview grvPayrollDetails is the nested child Gridview. Please help!
I followed this guide: Export Nested GridView (GridView inside GridView) to Excel in ASP.Net
And this is the Nested Gridview :
Nested Gridview
Change your following line GridView grvPayrollDetails = (GridView)grvPayroll.Rows[1].FindControl("grvPayrollDetails"); with below code
GridView grvPayrollDetails = null;
foreach (GridViewRow row in grvPayroll.Rows)
{
if (row.HasControls())
{
foreach (Control ctrl in row.Controls)
{
if (ctrl.ID == "grvPayrollDetails" && grvPayrollDetails != null)
{
grvPayrollDetails = (GridView)ctrl;
break;
}
}
if (grvPayrollDetails != null)
{
break;
}
}
}
you should modify your for loop to run for count - 1, and use if condition to check row.Cells should be >= 3
for (int j = 0; j < grvPayrollDetailscell.Rows.Count - 1; j++)
{
if(row.Cells.Count >= 3)
{
dt.Rows.Add(row.Cells[1].Text, row.Cells[2].Text, grvPayrollDetailscell.Rows[j].Cells[0].Text, grvPayrollDetailscell.Rows[j].Cells[1].Text);
Also makesure your dt.Columns have value before removing column at 0 index
if(dt.Columns.Count > 0)
{
dt.Columns.RemoveAt(0);
}
Try this:
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
protected void ExportExcel(object sender, EventArgs e)
{
grvPayroll.AllowPaging = false;
var grvPayrollDetails = new GridView();
for (var i = 0; i < grvPayroll.Rows.Count; i++)
{
grvPayrollDetails = (GridView)grvPayroll.Rows[i].FindControl("grvPayrollDetails");
grvPayrollDetails.AllowPaging = false;
BindGrid(SortField);
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=PayrollExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
grvPayrollDetails.AllowPaging = false;
this.BindGrid(SortField);
grvPayrollDetails.Font.Name = "Times New Roman";
grvPayrollDetails.BackColor = Color.Transparent;
grvPayrollDetails.GridLines = GridLines.Both;
grvPayrollDetails.RenderControl(hw);
Response.Write(Regex.Replace(sw.ToString(), "(<a[^>]*>)|(</a>)", " ", RegexOptions.IgnoreCase));
Response.Flush();
Response.End();
}
}

error when I export GridView to Excel

when I Export Grid View to Excel I have This message error
My dataBase is SQL Server and My table has 8000 rows
when i select just 1 row to gridview it export to excel without errors
but when i select all rows this problem appear
this is my code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
System.Data.SqlClient.SqlDataReader reader = objCalep.SelectAll(true, false, "[تاريخ الاستشهاد]");
// System.Data.SqlClient.SqlDataReader reader = objCCP.CPSelectNo(2700);
DataTable dataTable = new DataTable();
dataTable.Load(reader);
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//System.Data.Common.DbDataRecord drv = e.Row.DataItem as System.Data.Common.DbDataRecord;
DataRowView dataRowView = e.Row.DataItem as DataRowView;
DataRow drv = dataRowView.Row;
Object ob = drv["تاريخ الاستشهاد"];
if (!Convert.IsDBNull(ob))
{
DateTime dateTime = (DateTime)ob;
e.Row.Cells[4].Text = dateTime.ToString("dd/MM/yyyy");
e.Row.Cells[4].Width = 100;
}
}
}
protected void btn_Add_Click(object sender, ImageClickEventArgs e)
{
PrepareGridViewForExport(GridView1);
ExportGridView();
}
private void ExportGridView()
{
string attachment = "attachment; filename=حلب.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
private void PrepareGridViewForExport(Control gv)
{
LinkButton lb = new LinkButton();
Literal l = new Literal();
string name = String.Empty;
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(LinkButton))
{
l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(CheckBox))
{
l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
PrepareGridViewForExport(gv.Controls[i]);
}
}
}
and this is image error Error message
Well, I can't read much of that error message, but I'm guessing that the ViewState data for the grid is larger than the maximum request length configured on your site (I believe the default is 4MB).
Try changing <httpRuntime maxRequestLength="158334976" /> in the <system.web> section of your web.config.
If that works, you could leave the maxRequestLength at a high enough value, or disable ViewState for your grid, though you'd have to retrieve the data from the database again after the postback.

Merging of Header in Gridview

I encountered a problem in Gridview, I cannot merge the headers if the Gridview has no record, but if the Gridview contain a record, the headers are merging.
Here is my codes that I used to merge the headers in the Gridview
protected void grdWorkExperience_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView oGridView = (GridView)sender;
GridViewRow oGridViewRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell oTableCell = new TableCell();
oTableCell.Text = string.Empty;
oTableCell.ColumnSpan = 2;
oTableCell.BorderColor = System.Drawing.Color.White;
oGridViewRow.Cells.Add(oTableCell);
oTableCell = new TableCell();
oTableCell.Text = "Inclusive Dates(mm/dd/yyyy)";
oTableCell.ColumnSpan = 2;
oTableCell.Font.Bold = true;
oTableCell.Font.Size = 9;
oTableCell.Font.Name = "Verdana";
oTableCell.HorizontalAlign = HorizontalAlign.Center;
oTableCell.BackColor = System.Drawing.Color.FromArgb(0x33, 0x66, 0xCC);
oTableCell.ForeColor = System.Drawing.Color.White;
oTableCell.BorderColor = System.Drawing.Color.Gray;
oGridViewRow.Cells.Add(oTableCell);
oTableCell = new TableCell();
oTableCell.BorderColor = System.Drawing.Color.White;
oTableCell.ColumnSpan = 13;
oGridViewRow.Cells.Add(oTableCell);
oGridView.Controls[0].Controls.AddAt(0, oGridViewRow);
}
}
I placed that function in onRowCreated event of Gridview
What should I do to merge the Headers even if the Gridview has no record?
Move the code from OnRowCreated event to Load event of the Window/Control/Page

how to export a grid view in to excel?

hi i am developing an application where i am using a grid to dispaly data and adding a dynamic datatable as the header of the gridview and iam using the following code to export the grid view into excel but i am unable get the datatable which was added dynamically to the grid into the excel. the code i am using is:
Response.AddHeader("content-disposition", "attachment;filename=Report.xls");
Response.Charset = String.Empty;
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.DataBind();
GridView1.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
is thee any other method to follow.
Thanks in advance!
I don't see where you are adding the dynamic datatable as the header?? This should come after the databind and before the GridView1.RenderControl(hw);
try this one in the button click event
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename= {0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
gvdetails.DataBind();
//Change the Header Row back to white color
gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < gvdetails.HeaderRow.Cells.Count; i++)
{
gvdetails.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in gvdetails.Rows)
{
gvrow.BackColor = Color.White;
if (j <= gvdetails.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
this will export gridview in formatted output file
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=gridSample.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//to export all pages
gridSample.AllowPaging = false;
gridSample.DataSource = progress.getSample();
gridSample.DataBind();
//bind again
gridSample.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in gridSample.HeaderRow.Cells)
{
cell.BackColor = gridSample.HeaderStyle.BackColor;
}
foreach (GridViewRow row in gridSample.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = gridSample.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = gridSample.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
gridSample.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}

Categories