I have tow grid views master grid is gridpurchase and child grid is gvItems
I am trying to hide some columns in gvItems when exporting the grids to excel file.
i have tried the below code but it didn't work
Exporting code
protected void btnexcel_Click(object sender, EventArgs e)
{
gridpurchase.DataSource = po.GetPurchaseOrders();
gridpurchase.DataBind();
GridView gvItems = gridpurchase.FindControl("gvItems") as GridView;
gvItems.Columns[0].Visible = false;
gridpurchase.GridLines = GridLines.Both;
foreach (GridViewRow row in gridpurchase.Rows)
{
foreach (TableCell cell in row.Cells)
{
for (int i = cell.Controls.Count - 1; i >= 0; i--)
{
if (cell.Controls[i] is Image)
{
Image img = cell.Controls[i] as Image;
if (img.ImageUrl.Contains("plus.png") || img.ImageUrl.Contains("minus.png"))
{
cell.Controls.RemoveAt(i);
}
}
}
}
}
gridpurchase.Caption = "Purchase Orders Report";
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
System.IO.StringWriter strWriter = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
curContext.Response.Clear();
curContext.Response.Buffer = true;
curContext.Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("PurchaseOrdersReport", System.Text.Encoding.UTF8) + ".xls");
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=UTF-8>");
strWriter = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
gridpurchase.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
}
Grid-view
<asp:GridView ID="gridpurchase" OnRowCommand="gridpurchase_RowCommand" OnRowDataBound="gridpurchase_RowDataBound" DataKeyNames="RequisitionID" GridLines="None" runat="server" CssClass="table text-nowrap" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Preview">
<ItemTemplate>
<asp:Image ID="imgPlus" runat="server" AlternateText="" ImageUrl="img/plus.png" Style="cursor: pointer" />
<asp:Panel ID="pnlproducts" runat="server" Style="display: none">
<asp:GridView ID="gvItems" CssClass="table table-bordered" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ItemName" HeaderText="Item Name" SortExpression="ItemName" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="SupplierName" HeaderText="Supplier Name" SortExpression="SupplierName" />
<asp:BoundField DataField="PurchaseOrderCode" HeaderText="Purchase Order Code" SortExpression="PurchaseOrderCode" />
</Columns>
</asp:GridView>
According to your markup, there is a gvItems GridView inside of each row of gridpurchase. You can retrieve every child GridView in your main loop:
foreach (GridViewRow row in gridpurchase.Rows)
{
GridView gvItems = row.FindControl("gvItems") as GridView;
gvItems.Columns[0].Visible = false;
foreach (TableCell cell in row.Cells)
{
...
}
}
Change your foreach loop like this
gridpurchase.HeaderRow.Cells[0].Visible = false;
foreach (GridViewRow row in gridpurchase.Rows)
{
row.Cells[0].Visible = false;
}
This will remove the first column from your asp:GridView
Related
I have a grid view showing product images:
<form id="form1" runat="server">
<asp:Button ID="btnDownload" runat="server" CssClass="dist-down-button" Text="Download Selected" OnClick="DownloadFiles" />
<asp:Button ID="Button1" runat="server" CssClass="dist-down-button" Text="Download All" OnClick="DownloadAll" />
<asp:GridView ID="GridView1" runat="server" CssClass="mydatagrid" PagerStyle-CssClass="pager" HeaderStyle-CssClass="header" RowStyle-CssClass="rows" AllowPaging="True" OnPageIndexChanging="datagrid_PageIndexChanging" AutoGenerateColumns="false" EmptyDataText="No files available">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
<asp:Label ID="lblFilePath" runat="server" Text='<%# Eval("Value") %>' Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Text" HeaderText="Image Name" />
</Columns>
</asp:GridView>
</form>
Binding function: (matches all the files in the products folder with the product images list from database and show matching products)
protected void BindData()
{
images = GetProductImages();
string[] filePaths = Directory.GetFiles(Server.MapPath("~/upload/Products/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
if (images.IndexOf(Path.GetFileName(filePath)) > -1)
{
files.Add(new ListItem(Path.GetFileName(filePath), filePath));
}
}
GridView1.DataSource = files;
GridView1.DataBind();
}
protected void datagrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
Download All function: (look for the gridview list and download all the files listed)
protected void DownloadAll(object sender, EventArgs e)
{
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName(ProductUrl);
foreach (GridViewRow row in GridView1.Rows)
{
string filePath = (row.FindControl("lblFilePath") as Label).Text;
zip.AddFile(filePath, ProductUrl);
}
Response.Clear();
Response.BufferOutput = false;
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(Response.OutputStream);
Response.End();
}
}
When I click on Download All button it was downloading all the files correctly. BUT after I added the pagination the download all is now only downloading the current page.
Note: The checkbox is for selected download function. As you see I am not looking for checkboxes checked in the DownloadAll function.
Does anyone know why is this happening eventhough I am not looking for any checkbox in my function?
You could turn off paging and re-binding the GridView before exporting:
protected void DownloadAll(object sender, EventArgs e)
{
GridView1.AllowPaging = false;
BindData();
// ... your code
GridView1.AllowPaging = true;
BindData();
}
In Download All function, you have clearly writing that...take file path
only from gridview.. After the pagination...so it only take Current
Page Gridview data...not pickup all the data..
foreach (GridViewRow row in GridView1.Rows)
{
string filePath = (row.FindControl("lblFilePath") as Label).Text;
zip.AddFile(filePath, ProductUrl);
}
Solution:-
So, Whenever you binding the Gridview that time hold all data in
ViewState..
gridView.DataSource = dt;
gridView.DataBind();
ViewState["DownLoadGridData"]=dt as DataTable;
DataTable dt = ViewState["DownLoadGridData"] as DataTable;
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
if (row[FilePath] != null) // This will check the null values also (if you want to check).
{
// then add filepath
string filePath = row[FilePath].ToString();
zip.AddFile(filePath, ProductUrl);
}
}
}
Note:- you can develop your own logic also
Here is my current grid view.
<asp:GridView ID="grdIndexGroupMap" runat="server" AutoGenerateColumns="False" DataKeyNames="IndexName"
OnRowCancelingEdit="grdIndexGroupMap_RowCancelingEdit" OnRowDataBound="grdIndexGroupMap_RowDataBound"
OnRowEditing="grdIndexGroupMap_RowEditing" OnRowUpdating="grdIndexGroupMap_RowUpdating"
OnRowCommand="grdIndexGroupMap_RowCommand" ShowFooter="True" OnRowDeleting="grdIndexGroupMap_RowDeleting"
CellPadding="1" CellSpacing="1" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<%--IndexName--%>
<asp:TemplateField HeaderText="IndexName" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:DropDownList ID="cmbIndexName" runat="server" DataTextField="LocationName" DataValueField="IndexId"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblIndexName" runat="server" Text='<%# Eval("IndexName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="cmbNewIndexName" runat="server" DataTextField="IndexName" DataValueField="IndexId"></asp:DropDownList>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
How do replace the DropDownList with a dropdown where I can select multiple items?
A checkboxlist in dropdownlist or a listbox with multiselect in dropdown. When selected will show comma seperated values.
Tried a couple of ways but wont work.
here is my databound method:
protected void grdIndexGroupMap_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList cmbIndexName = (DropDownList)e.Row.FindControl("cmbIndexName");
if (cmbIndexName != null)
{
cmbIndexName.DataSource = _Indexes;
cmbIndexName.DataTextField = "IndexName";
cmbIndexName.DataValueField = "IndexId";
cmbIndexName.DataBind();
cmbIndexName.SelectedValue = grdIndexGroupMap.DataKeys[e.Row.RowIndex].Values[1].ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList cmbNewIndexName = (DropDownList)e.Row.FindControl("cmbNewIndexName");
cmbNewIndexName.DataSource = _Indexes;
cmbNewIndexName.DataBind();
}
}
I am using ASP.Net, C#
How about:
<asp:TemplateField HeaderText="IndexName" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:PlaceHolder id="phListContainer" runat="server" />
</EditItemTemplate>
then in your code-behind:
if (e.Row.RowType == DataControlRowType.DataRow)
{
phListContainer = (PlaceHolder)e.Row.FindControl(phListContainer);
if (phListContainer != null)
{
//Adding a DropDownList
var cmbIndexName = new DropDownList();
cmbIndexName.DataSource = _Indexes;
cmbIndexName.DataTextField = "IndexName";
cmbIndexName.DataValueField = "IndexId";
cmbIndexName.DataBind();
cmbIndexName.SelectedValue = grdIndexGroupMap.DataKeys[e.Row.RowIndex].Values[1].ToString();
phListContainer.Controls.Add(cmbIndexName);
// OR
//Adding a CheckBoxList;
cmbIndexName = new CheckBoxList();
cmbIndexName.DataSource = _Indexes;
cmbIndexName.DataTextField = "IndexName";
cmbIndexName.DataValueField = "IndexId";
cmbIndexName.DataBind();
phListContainer.Controls.Add(cmbIndexName);
}
}
Then you can get the controls by
var cbList = (CheckBoxList)e.Row.FindControl(phListContainer).Controls[0];
and then you can loop through and find the checked boxes
for(int i = 0; i < cbList.Items.Count; ++i)
{
if(cbList.Items[i].Selected)
//Do stuff
}
my.ascx >>
<telerik:RadAjaxPanel ID="ajaxPanel_Header" runat="server">
<asp:Button ID="Button_ExportToExcel" runat="server" Text="" CssClass="ExportToExcel" UseSubmitBehavior="False" OnClick="Button_ExportToExcel_Click" />
<telerik:RadGrid ID="grid_Permission" runat="server" AutoGenerateColumns="False" PageSize="200" GridLines="None" CellSpacing="0" AllowSorting="True" ShowGroupPanel="True" ShowFooter="True" OnNeedDataSource="grid_Permission_NeedDataSource" OnItemDataBound="grid_Permission_ItemDataBound" OnDetailTableDataBind="grid_Permission_DetailTableDataBind" OnItemCommand="grid_Permission_ItemCommand">
...
...
...
<MasterTableView CellSpacing="-1" NoMasterRecordsText="Kayıt bulunamadı." DataKeyNames="MrkDocHeaderId,ProdStoreOrderDetailId,IsStoreOutSubscribed,ProdStoreStockTypeId" HierarchyLoadMode="ServerOnDemand" Name="tbl_Master" EnableHeaderContextMenu="True" GroupLoadMode="Client" AllowPaging="True" PageSize="10">
...
...
<telerik:GridBoundColumn HeaderText="Onay Durumu" DataField="IsStoreOutSubscribedText" FilterControlAltText="Filter IsStoreOutSubscribedText column" UniqueName="IsStoreOutSubscribedText" Visible="False" Exportable="true">
<ColumnValidationSettings>
<ModelErrorMessage Text="" />
</ColumnValidationSettings>
</telerik:GridBoundColumn>
</MasterTableView>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
my.ascx.cs >>
protected void Button_ExportToExcel_Click(object sender, EventArgs e)
{
//RadGrid grid = grid_Permission;
if (grid_Permission != null)
{
if (grid_Permission.Items.Count > 0)
{
try
{
//grid_Permission.ExportSettings.Excel.Format = GridExcelExportFormat.Biff;
grid_Permission.ExportSettings.FileName = string.Format("MamulDepoUrunRaporu_{0}", DateTime.Now);
grid_Permission.ExportSettings.IgnorePaging = true;
grid_Permission.ExportSettings.OpenInNewWindow = true;
grid_Permission.ExportSettings.ExportOnlyData = true;
grid_Permission.MasterTableView.UseAllDataFields = true;
//grid_Permission.MasterTableView.GetColumn("img_IsStoreOutSubscribed").Visible = false;
grid_Permission.MasterTableView.ExportToExcel();
}
finally
{
}
}
}
}
Here is my question:
I have a telerik radgrid. I want to export to excel some fields of this grid, visible or not.
But in my exported file i cannot see the visible=false field values even they are marked Exportable="true"
I tried to change column visibilty to true before the export and set false again etc. nothing is changed.
Any ideas about the reason?
I am not sure about the origin of your problem, however this is how I do export to excel and it works.
protected void ExpExcel_Click(object sender, EventArgs e)
{
//exclude columns from being exported in excel
foreach (GridColumn col in RadGrid1.MasterTableView.Columns)
{
if ((col.UniqueName.Contains("EditCommandColumn")) ||
(col.UniqueName.Contains("column1")))
{
col.Display = false;
}
else
{
col.Display = true;
}
}
//format content to be exported in excel
foreach (GridFilteringItem item in RadGrid1.MasterTableView.GetItems(GridItemType.FilteringItem))
item.Visible = false;
//the other settings you need...
RadGrid1.ExportSettings.FileName = "yourFileName;
RadGrid1.ExportSettings.ExportOnlyData = true;
RadGrid1.ExportSettings.Excel.Format = Telerik.Web.UI.GridExcelExportFormat.ExcelML;
//example of renaming column header in excel
RadGrid1.MasterTableView.Columns.FindByUniqueName("something").HeaderText = "something else";
//finally export the columns
RadGrid1.MasterTableView.ExportToExcel();
}
Let us know if this is of help.
I am trying to do when the checkbox column in my gridview is marked, I get the row index. My gridview is in a repeater and when I setup the gridview, I put a DataKeyNames:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<asp:Panel ID="pBody1" runat="server" CssClass="cpBody">
<asp:Label ID="lblBodyText1" runat="server" />
<!-- Grid view to show products based on each category -->
<asp:GridView ID="gvProduct" runat="server" AutoGenerateColumns="False" Width="998px" CellPadding="4" ForeColor="#333333" GridLines="None" ShowHeader="False" DataKeyNames="id">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="cbCheckRow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="Name" ItemStyle-Width="600px" />
<asp:BoundField DataField="categoryName" HeaderText="Category" />
<asp:TemplateField HeaderText="Quantity" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:TextBox ID="tbQuantity" runat="server" Width="60" Text='<%# DataBinder.Eval(Container.DataItem, "inventoryQuantity") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
<asp:CollapsiblePanelExtender ID="cpe1" runat="server" TargetControlID="pBody1" CollapseControlID="pHeader1"
ExpandControlID="pHeader1" Collapsed="true" ImageControlID="imgArrows1"
CollapsedImage="~/Images/downarrow.jpg"
ExpandedImage="~/Images/uparrow.jpg" TextLabelID="lblHeaderText1" CollapsedText="Show"
ExpandedText="Hide" CollapsedSize="0"
ScrollContents="false">
</asp:CollapsiblePanelExtender>
</ItemTemplate>
</asp:Repeater>
<asp:LinkButton ID="lbnConfirm" runat="server" class="btn dark" style="float: right" OnClick="lbnConfirm_Click">Confirm</asp:LinkButton>
When my lbnConfirm is onclick, I perform this to get the row index and store them into a list:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
GridView gv = (GridView)Repeater1.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
GridViewRow row = gv.SelectedRow;
string prodID = this.gv.DataKeys[row].Value.ToString();
List<DistributionStandardPackingUnitItems> distSPUList = new List<DistributionStandardPackingUnitItems>();
//Store the prodIDs into list
}
}
}
When I run the page, it told me object reference is not set to an instance at this line:
foreach (GridViewRow gr in gv.Rows)
Also the gv of this line:
string prodID = this.gv.DataKeys[row].Value.ToString();
told me that the gv does not contain a definition of missing reference. I thought I declared at the code above?
Edited Portion:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
string prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
tempList.Add(prodID);
for (int count = 0; count < tempList.Count; count++)
{
lblTest.Text = tempList[count] + ",";
}
}
}
}
}
}
Your approach is right, however you need to consider few more things:
You have to loop through the Repeater's items and find the Panel in
each item.
You have to find the GridView inside the Panel, not in the Repeater.
You have to find the DataKey Value by RowIndex, not by row.
EDIT : To test, add a Label outside the repeater:
<asp:Label ID="lblTest" runat="server" Text=""></asp:Label>
Also change the code to display Id in the label.
After rewriting lbnConfirm_Click() method, it should look like below:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
List<string> tempList = new List<string>();
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//GridViewRow row = gv.SelectedRow;
string prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
List<DistributionStandardPackingUnitItems> distSPUList = new List<DistributionStandardPackingUnitItems>();
//Store the prodIDs into list
tempList.Add(prodID);
}
}
}
}
lblTest.Text = string.Join(",", tempList);
}
The code above worked fine in my test! Only you have to be careful not to rebind the repeater at postback in Page_Load().
Hope it helps!
get the row index in the RowDataBound event :
protected void gvProduct_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.commandName=="select")
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = e.Row.RowIndex;
CheckBox chk = (CheckBox)e.Row.FindControl("cbCheckRow");
int code = Convert.ToInt32(this.gvProduct.DataKeys[e.Row.RowIndex].Value);
}
}
}
I have a gridview with a button for exporting it's data to an Excel file. When the button is clicked, I receive the following error:
Control 'gvLogNotice' of type 'GridView' must be placed inside a form tag with runat=server.
However, the Grid is within a form tag, I tried it both using a MasterPage and using a page w/o a MasterPage and still get the same error.
This is my Gridview snippet w/ button:
<form id="form1" runat="server">
<div style="width:600px;">
<asp:GridView ID="gvLogNotice"
runat="server"
AutoGenerateColumns="false"
ShowFooter="false"
OnRowCancelingEdit="gvLogNotice_RowCancelingEdit"
OnRowEditing="gvLogNotice_RowEditing"
OnRowUpdating="gvLogNotice_RowUpdating"
onpageindexchanging="gvLogNotice_PageIndexChanging"
OnRowDataBound="gvLogNotice_RowDataBound"
EmptyDataText="There are no data records to display."
DataKeyNames="LogNoticeID"
AllowPaging="true"
PageSize="10"
AllowSorting="true"
OnSorting="gvLogNotice_sorting"
Width="700px">
<Columns>
<asp:TemplateField HeaderText="Log No." Visible="false">
<ItemTemplate>
<%#Eval("LogNoticeID")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLogNoticeID" runat="server" Enabled="false" Text=' <%#Eval("LogNoticeID") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Log Date" SortExpression="DateLogged">
<ItemTemplate>
<%#Eval("DateLogged")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDateLogged" runat="server" Text=' <%#Eval("DateLogged") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Log Description" HeaderStyle-Width="50px" sortexpression="LogNoticeDescript">
<ItemTemplate>
<%#Eval("LogNoticeDescript")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLogNoticeDescript" runat="server" Text=' <%#Eval("LogNoticeDescript") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Responsible Party" sortexpression="ResponsibleParty">
<ItemTemplate>
<%#Eval("ResponsibleParty")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtResponsibleParty" runat="server" Text=' <%#Eval("ResponsibleParty") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Planned Date" SortExpression="PlannedDate" >
<ItemTemplate>
<%#Eval("PlannedDate")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPlannedDate" runat="server" Text=' <%#Eval("PlannedDate") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Case Number" SortExpression="CaseNumber">
<ItemTemplate>
<%#Eval("CaseNumber")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCaseNumber" runat="server" Text=' <%#Eval("CaseNumber") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Log Status" SortExpression="LogStatus">
<ItemTemplate>
<%#Eval("LogStatus")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLogStatus" runat="server" Text=' <%#Eval("LogStatus") %>'></asp:TextBox>
<asp:RangeValidator ID="rgvtxtLogStatus" runat="server" ControlToValidate="txtLogStatus" MaximumValue="1" MinimumValue="0" Text="Only a Value of 1 or 0 is allowed." />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="images/edit.png" Width="25"
Height="25" CommandName="Edit" />
<%-- <asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/img/delete.png" CommandName="Delete"
OnClientClick="return confirm('Are you sure want to delete record?')" />--%>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div><asp:Button runat="server" ID="btnExport" Text="Export to Excel"
onclick="btnExport_Click" /></div>
</form>
...This is the code behind the button:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
gvLogNotice.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
...Second Approach: I also tried the following and I got an error that only one Form may exists:
protected void btnExport_Click(object sender, EventArgs e)
{
try
{
Response.ClearContent();
string attachment = "attachment; filename=MyExelFile.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter strWrite = new StringWriter();
HtmlTextWriter htmWrite = new HtmlTextWriter(strWrite);
HtmlForm htmfrm = new HtmlForm();
gvLogNotice.Parent.Controls.Add(htmfrm);
htmfrm.Attributes["runat"] = "server";
htmfrm.Controls.Add(gvLogNotice);
htmfrm.RenderControl(htmWrite);
Response.Write(strWrite.ToString());
Response.Flush();
Response.End();
}
catch (Exception ex) { }
}
Could I please get some help as to what I'm missing here? Thank you in Advance.
try this code on export button:
protected void btnExport_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);
//To Export all pages
GridView1.AllowPaging = false;
GridViewBind();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.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(Control control)
{
/* Verifies that the control is rendered */
}
If you like to use 3rd party component then refer to this article.
http://www.codeproject.com/Articles/8411/C-class-library-for-exporting-data-to-CSV-Excel-fi
Try this
protected void Button2_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
private void ExportToExcel(DataTable dt)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Sheet1.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
GridView dgGrid = new GridView();
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in dgGrid.HeaderRow.Cells)
{
cell.BackColor = dgGrid.HeaderStyle.BackColor;
}
foreach (GridViewRow row in dgGrid.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = dgGrid.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = dgGrid.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
dgGrid.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();
}
}
This happens when you don't have the VerifyRenderingInServerForm in your code.
Simply put this snippet after your export code and it will go away.
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}