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.
Related
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
The buttonfield with command EDIT doesn't work until I put
OnRowEditing="grdviewContractorTypes_RowEditing"
Problem:
I wrote this code
<asp:GridView runat="server" ID="grdviewContractorTypes" OnRowEditing="grdviewContractorTypes_RowEditing" OnRowCommand="grdviewContractorTypes_RowCommand" DataKeyNames="pk_ContractorTypes_ContractorTypeID" AutoGenerateColumns="false" CssClass="table table-condensed table-bordered table-striped table-responsive">
<Columns>
<asp:BoundField DataField="pk_ContractorTypes_ContractorTypeID" HeaderText="ID" />
<asp:BoundField DataField="ContractorTypeName" HeaderText="Contractor Type" />
<asp:ButtonField CommandName="edit" ImageUrl="~/assets/global/images/shopping/edit.png" ButtonType="Image" ControlStyle-Width="25px" ControlStyle-Height="25px" />
</Columns>
</asp:GridView>
.cs
protected void grdviewContractorTypes_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "edit")
{
byte ContractorTypeID = Convert.ToByte(grdviewContractorTypes.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
//HFActID.Value = ID.ToString();
btnAddContractorType.Visible = false;
btnUpdated.Visible = true;
DataTable dt = MngContractorTypes.SelectContractorTypesByContractorTypeID(ContractorTypeID);
DataRow r = dt.Rows[0];
txtBoxContractorTypeName.Text = r["ContractorTypeName"].ToString();
HdnFieldContractorTypeID.Value = r["pk_ContractorTypes_ContractorTypeID"].ToString();
//txtSearch.Text = "Testing...";
//Response.Write("DONE");
}
}
catch (Exception ex)
{
Response.Write(Convert.ToString(ex.Message));
}
}
The above code runs when I click button field with 'edit' command in DEBUGGER but doesn't do anything in actual, on screen until I put this.
protected void grdviewContractorTypes_RowEditing(object sender, GridViewEditEventArgs e)
{
}
I have created user control named CRE.ascx,this control has 3 dropdownlist.
First dropdownlist bind data on pageload.Second and third based on SelectedIndexChanged.
<table cellspacing="0" cellspading="0" style="width:550px;height:30px;">
<tr>
<td style="width:30%;">
<asp:DropDownList ID="ddlCRE" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlCRE_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlDataPoints" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlDataPoints_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlErrorCode" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlErrorCode_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:10%;">
<asp:TextBox ID="tbxErrorScore" runat="server" style="height:17px;border:0px;font-family:'Segoe UI';font-size:13px;font-weight:500;color:white;background-color:#333333;
width:65px;" ReadOnly="true"> </asp:TextBox>
</td>
</tr>
</table>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Get Ticket Type Values
dbtickettype = helpdsktcktusrHandler.GetTicketType("DPT0001");
ddlCRE.DataSource = dbtickettype;
ddlCRE.DataValueField = "Type_ID";
ddlCRE.DataTextField = "Type_Name";
ddlCRE.DataBind();
ddlCRE.Items.Insert(0, new ListItem("Select Type", "SLCT0000"));
}
else
{
}
}
protected void ddlCRE_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedTypeID = ddlCRE.SelectedValue.ToString();
try
{
if (selectedTypeID == "SLCT0000")
{
ddlDataPoints.Items.Clear();
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketCategory = helpdsktcktusrHandler.GetTicketCategoryDetails(selectedTypeID);
//Binding Ticket Type values to Listbox
ddlDataPoints.DataSource = dbticketCategory;
ddlDataPoints.DataValueField = "Category_ID";
ddlDataPoints.DataTextField = "Category_Name";
ddlDataPoints.DataBind();
ddlDataPoints.Items.Insert(0, new ListItem("Select Category", "SLCT0000"));
//Clear Items
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlDataPoints_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCatID = ddlDataPoints.SelectedValue.ToString();
try
{
if (selectedCatID == "SLCT0000")
{
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketSubCategory = helpdsktcktusrHandler.GetTicketSubCategoryDetails(selectedCatID);
//Binding Ticket Type values to Listbox
ddlErrorCode.DataSource = dbticketSubCategory;
ddlErrorCode.DataValueField = "Sub_Category_ID";
ddlErrorCode.DataTextField = "Sub_Category_Name";
ddlErrorCode.DataBind();
ddlErrorCode.Items.Insert(0, new ListItem("Select Subcategory", "SLCT0000"));
//Clear Items
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlErrorCode_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedSubcatID = ddlErrorCode.SelectedValue.ToString();
try
{
if (selectedSubcatID == "SLCT0000")
{
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketIssues = helpdsktcktusrHandler.GetTicketIssueDetails(selectedSubcatID);
////Binding Ticket Type values to Listbox
//ddlstIssue.DataSource = dbticketIssues;
//ddlstIssue.DataValueField = "IssueID";
//ddlstIssue.DataTextField = "Issue_Name";
//ddlstIssue.DataBind();
tbxErrorScore.Text = dbticketIssues.Rows[0][1].ToString();
}
}
catch (Exception ex)
{
}
}
then register directive and an instance of the user control added to the page.
In this main page, i have added one Gridview, user control UC1 and two buttons
included in the ItemTemplate.
<%# Register src="~/CRE.ascx" TagName="InsertNewCRE" TagPrefix="uc1" %>
<asp:UpdatePanel ID="MainUpdatePanel" runat="server">
<ContentTemplate>
<div id="dvsubCRE" class="dvsubCRE" runat="server">
<!-----[[[ GRIDVIEW ADDING CRE ]]]----->
<div id="dvAddingErrorInfo" class="dvAddingErrorInfo">
<!-- LOAD CRE DROPDOWN INFO GRID -->
<asp:GridView ID="gvCREInfo" runat="server" CssClass="gvErrorInfo" AlternatingRowStyle-CssClass="" ShowFooter="false" ShowHeader="false"
EnableViewState="True" GridLines="None" EmptyDataText="No records found" AutoGenerateColumns="true" CaptionAlign="Left" CellPadding="0"
ShowHeaderWhenEmpty="True" OnRowCreated="gvCREInfo_RowCreated" OnRowCommand="gvCREInfo_RowCommand" >
<Columns>
<asp:BoundField DataField="RowNumber" />
<asp:TemplateField ItemStyle-Width="25%" ItemStyle-Height="20px">
<ItemTemplate>
<uc1:InsertNewCRE id="UC1InserCRE" runat="server" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgbtnAddCRE" runat="server" Width="20px" Height="20px" value="" ImageUrl="~/Images/Tracker/add.png"
CommandName="ButtonAddCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<asp:ImageButton ID="imgbtnReoveCRE" runat="server" Width="20px" Height="20px" value="" Visible="false" ImageUrl="~/Images/Tracker/delete.png" CommandName="ButtonRemoveCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!-- LOAD CRE DROPDOWN INFO GRID CLOSE -->
</div>
<!-----[[[ GRIDVIEW ADDING CRE CLOSE ]]]----->
</div>
</ContentTemplate>
</asp:UpdatePanel>
When main page loads, user control UC1 loaded in the gridview and pull out the data from CRE.ascx page.I have bind dummy data on page load to the gridview.Add new row along with user control mentioned in the RowCommand.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
gvCREInfo.DataSource = dt;
gvCREInfo.DataBind();
}
else
{
}
}
catch (Exception ex)
{
}
}
protected void gvCREInfo_RowCommand(object sender, GridViewCommandEventArgs e)
{
#region ADD NEW CRE ROW
if (e.CommandName == "ButtonAddCRERow")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvCREInfo.Rows[index];
int count = gvCREInfo.Rows.Count;
DataRow drCurrentRow = null;
UserControl UC1 = (UserControl)(row.Cells[0].FindControl("UC1InserCRE"));
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
for (int i = 0; i <= (count - 1); i++)
{
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows.Add(drCurrentRow);
}
gvCREInfo.DataSource = dtCurrentTable;
gvCREInfo.DataBind();
}
#endregion
}
When i run this code working fine and i changed the first dropdownlist
it will pull data and bind to the second, like wise third one also.But when i click the add button selected data lost in the first row and second row control added not with data.How to retain existing selected data and load user control along with data it should not loss data event post back.Please help me and sort out this.
![enter image description here][1]
http://i.stack.imgur.com/wdYZv.jpg
Please help me with following, just something weird is going on.
I have a gridview with paging where the first column is filled with checkboxes.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="..." DataKeyNames="EventID" EnableViewState="false"
GridLines="None" AllowSorting="True"
AllowPaging="True" Width="100%"
onpageindexchanging="GridView1_PageIndexChanging"
onprerender="GridView1_PreRender">
<HeaderStyle Wrap="false" />
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left">
<HeaderTemplate>
<asp:CheckBox ID="SelectAllEvs" runat="server" EnableViewState="false" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="EventSelector" runat="server" EnableViewState="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ... >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField ... >
</asp:BoundField>
<asp:BoundField ... >
</asp:BoundField>
</Columns>
</asp:GridView>
CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["PageIndex"] != null)
{
GridView1.PageIndex = Convert.ToInt32(Session["PageIndex"]);
}
}
}
protected void GridView1_PreRender(object sender, EventArgs e)
{
// loading checkbox values from the session collection
GridView gv = (GridView)sender;
LoadCheckboxState(gv);
Session["PageIndex"] = gv.PageIndex;
}
private void LoadCheckboxState(GridView gv)
{
for (int i = 0; i < gv.Rows.Count; i++)
{
var chkBox = GridView1.Rows[i].FindControl("EventSelector") as CheckBox;
int id = gv.PageIndex * gv.PageSize + i;
if (SelectedIndexes.Contains(id))
{
chkBox.Checked = true;
}
else
{
chkBox.Checked = false;
}
}
}
private List<int> SelectedIndexes
{
get
{
if(Session["selectedRows"] == null)
{
Session["selectedRows"] = new List<int>();
}
return (List<int>)Session["selectedRows"];
}
}
private void SaveCheckboxState(GridView gv)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
var chkBox = GridView1.Rows[i].FindControl("EventSelector") as CheckBox;
int id = gv.PageIndex * gv.PageSize + i;
if (chkBox.Checked)
{
//see if we have an id added already
if (!SelectedIndexes.Contains(id))
{
SelectedIndexes.Add(id);
}
}
else
{
if (SelectedIndexes.Contains(id))
{
SelectedIndexes.Remove(id);
}
}
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
// saving current page checkbox values to the session collection
GridView gv = (GridView)sender;
SaveCheckboxState(gv);
GridView1.PageIndex = e.NewPageIndex;
}
When I first get to my page I check some checkboxes and then press F5. Apparently after pressing it I dont have any values in SelectediIndexes and all unselected checkboxes must be checked = false on the PreRender stage but they appear checked after all this. And the problem of the same nature: I checked some on the first page; went to the second page (currently having 2 indexes in the SelectedValues) and after pressing F5 the same I have checked the same checkboxes as on the first page, though they mustn't. I'm absolutely confused with this. How can I fix this? Thanx for any help.
I've found the reason to that strange behavior. I'm using Firrefox. And one of the features of this browser is saving state of some fields when refreshing the page. If you want to refresh a page fully you should refresh it with pressed shift button. Tested in Google Chrome - works just fine.
In my SQL query I retrieve 3 strings and the 3rd string has an URL. I created 2 templatefield contain labels and another template with an image. Now I want to set the values to the two labels and view the image by setting ImageUrl and display all the rows coming out from SQL query.
protected void Page_Load(object sender, EventArgs e)
{
//if (IsPostBack == false)
//{
// grdMaterial.DataBind();
//}
try
{
matType = int.Parse(Session["mattype"].ToString());
colorId = int.Parse(Session["color"].ToString());
matStyleId = int.Parse(Session["matstyle"].ToString());
try
{
matContent = Session["matContent"].ToString();
}
catch
{
panAval.Visible = true;
panNew.Visible = false;
dtab = new DBHELPER().getdataTable("SELECT [item_Id],[mat_Content],[mat_Image] FROM [item] WHERE [mat_Content]='" + matContent + "'");
//grdMaterial.DataSource = dtab;
//grdMaterial.DataBind();
}
catch (Exception ee)
{
}
}
protected void grdMaterial_Load(object sender, EventArgs e)
{
try
{
for (int i = 0; i < dtab.Rows.Count; i++)
{
//TextBox x = (TextBox)GridViewCarrinho.Rows[row.RowIndex].Cells[2].FindControl("txtQuantidade");
Label itemId = (Label)grdMaterial.FindControl("lblItemId");
itemId.Text = dtab.Rows[i]["item_Id"].ToString();
Label matContent = (Label)grdMaterial.FindControl("lblItemName");
matContent.Text = dtab.Rows[i]["mat_Content"].ToString();
Image itemImage = (Image)grdMaterial.FindControl("imgItemImage");
itemImage.ImageUrl = dtab.Rows[i]["mat_Image"].ToString();
}
}
catch (Exception ee)
{
}
}
This event: grdMaterial_Load does not seem necessary.
You can simply bind your datasource to your datagrid and simply customize the datagrid to get the image, and populate the labels.
Simply bind your ItemID and ItemName columns, then create a template field for the image as shown below...
<asp:GridView ID="grdMaterial" runat="server" DataKeyNames="item_Id" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="item_Id" HeaderText="Item Id" />
<asp:BoundField DataField="mat_Content" HeaderText="Item Name" />
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:Image ID="imgItemImage" runat="server" ImageUrl="<%# DataBinder.Eval(Container.DataItem, "mat_Image")) %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>