This is a migrated thread and some comments may be shown as answers.

Export Items in ItemTemplate

6 Answers 142 Views
Grid
This is a migrated thread and some comments may be shown as answers.
bradley baker
Top achievements
Rank 1
bradley baker asked on 22 Sep 2009, 09:35 PM
Trying to export data from a grid to xls/word/pdf but most of the data is in a ItemTemplate since we wanted to display the information in a diffrent format.  Is there anyway to get the data from the ItemTempate (All the information is coming from the same datasource) to the export.  (VB Example if you can).

6 Answers, 1 is accepted

Sort by
0
Todd Anglin
Top achievements
Rank 2
answered on 23 Sep 2009, 03:27 AM
Hello Bradley-

Have you had a chance to check out this demo:


It shows you exactly how to achieve that scenario (including VB code sample, too). In this demo, a RadGrid with several columns (including a GridTemplateColumn) is exported to PDF. The code here should show you the basic approach for exporting data even when ItemTemplates are used.

Let me know if that helps.
-Todd
0
bradley baker
Top achievements
Rank 1
answered on 23 Sep 2009, 03:52 PM
Yeah that uses one template for the col.  In my example I dont have any colums.  The entire row is a template
http://mmo-rpg.com/ss1.png
0
bradley baker
Top achievements
Rank 1
answered on 23 Sep 2009, 03:53 PM
Yeah I saw that but I dont have a col template my entire row is a template.
http://mmo-rpg.com/ss1.png
0
Accepted
Todd Anglin
Top achievements
Rank 2
answered on 23 Sep 2009, 05:15 PM
Let me make sure I understand your scenario correctly:

  • You have a RadGrid will all data in a single GridTemplateColumn (for "run time" display)
  • You want to export this data to (let's say) PDF
  • BUT you want the data to be exported as separate columns for different output formatting

Is that correct?

If that's the case, you'll essentially need to do two things when you click your "Export" button:

  1. In code, you'll need to programmatically redefine your Grid's columns (removing your template column, adding GridBoundColumns)
  2. Rebind your Grid
  3. Export the newly formatted Grid

Optionally, and perhaps an easier approach, you can define a second "hidden" RadGrid on your page. Then, during the Export event, you can bind the hidden RadGrid and call it's export function. Either approach will work. Check out the demo in this forum thread and see if it helps get you started on the right path:


Hope that helps!
-Todd
0
MUHAMMAD
Top achievements
Rank 1
answered on 31 May 2012, 09:26 PM
Todd,
(Using the latest version of Telerik controls. Q1, 2012)

I have a similar scenario where I need to export Grid content to PDF. The only difference is that I need to export only the selected rows from the grid with all of the data fields. The initial grid only displays few columns not all of the columns. Also I have to export with some style applied to the grid.
So I have to first loop through the selected rows in the first grid and then bind the second hidden grid to the new datasource with only selected rows and then call the export function for the second grid. Sound simple.

So I used your suggested approach where I can use a second Hidden Grid. But for some reason I still get all of the rows and not just selected rows. Have I defined my itemtemplate correctly for the second hidden grid?

Thanks in advance.

//Declare a global DataTable dtTable       
        public static DataTable dtTable;
        bool isPdfExport = false;
        public static ArrayList arrayList = new ArrayList();
  
  
        //Get the connectionstring from the webconfig and declare a global SqlConnection "SqlConnection"   
        public static string connectionString = ConfigurationManager.ConnectionStrings["TestRadControls"].ConnectionString;
        public SqlConnection SqlConnection = new SqlConnection(connectionString);
  
        //Declare a global SqlDataAdapter SqlDataAdapter     
        public SqlDataAdapter SqlDataAdapter = new SqlDataAdapter();
  
        //Declare a global SqlCommand SqlCommand      
        public SqlCommand SqlCommand = new SqlCommand();
        /*Need this to update an existing record*/
        private static DataTable GetDataTable(string queryString)
        {
            String ConnString = ConfigurationManager.ConnectionStrings["TestRadControls"].ConnectionString;
            SqlConnection MySqlConnection = new SqlConnection(ConnString);
            SqlDataAdapter MySqlDataAdapter = new SqlDataAdapter();
            MySqlDataAdapter.SelectCommand = new SqlCommand(queryString, MySqlConnection);
  
            DataTable myDataTable = new DataTable();
            MySqlConnection.Open();
            try
            {
                MySqlDataAdapter.Fill(myDataTable);
            }
            finally
            {
                MySqlConnection.Close();
            }
  
            return myDataTable;
        }
  
        /*Need this to update an existing record*/
        private DataTable Agreements
        {
            get
            {
                object obj = this.Session["Agreements"];
                if ((!(obj == null)))
                {
                    return ((DataTable)(obj));
                }
                DataTable myDataTable = new DataTable();
                myDataTable = GetDataTable("SELECT LifeSciences_Agreement.AgreementID, LifeSciences_Agreement.GenericName, LifeSciences_Agreement.ClassificationComments, LifeSciences_Agreement.RationaleIssueLong, LifeSciences_Agreement.RationaleIssueShort, LifeSciences_Agreement.Strategy, LifeSciences_Agreement.AgreementDetailsLong, LifeSciences_Agreement.AgreementDetailsShort, LifeSciences_Agreement.AgreementDecisionNotes, LifeSciences_Agreement.AgreementReviewDate, LifeSciences_Agreement.AgreementStatus, LifeSciences_Agreement.RegistryDetails, LifeSciences_Agreement.PlannedEvaluation, LifeSciences_Agreement.Comments, LifeSciences_Agreement.Links, LifeSciences_Agreement.Reference, LifeSciences_Agreement.AdminApproved, LifeSciences_Agreement.RecordCreated, LifeSciences_Agreement.RecordModified, LifeSciences_Agreement.LastModifiedBy, LifeSciences_BrandName.BrandName, LifeSciences_Category.CategoryName, LifeSciences_Decision.DecisionName, LifeSciences_Country.Country, LifeSciences_Classification.ClassificationName, LifeSciences_RegistryStatus.RegistryStatusName, LifeSciences_RegistryRequirement.RegistryRequirementName, LifeSciences_Indication.IndicationName, LifeSciences_Payer.PayerName, LifeSciences_TherapeuticArea.TherapeuticAreaName, LifeSciences_Type.TypeName, LifeSciences_Company.CompanyName FROM LifeSciences_Agreement LEFT OUTER JOIN LifeSciences_Agreement_Company ON LifeSciences_Agreement.AgreementID = LifeSciences_Agreement_Company.AgreementID LEFT OUTER JOIN LifeSciences_BrandName ON LifeSciences_Agreement.BrandID = LifeSciences_BrandName.BrandID LEFT OUTER JOIN LifeSciences_Category ON LifeSciences_Agreement.CategoryID = LifeSciences_Category.CategoryID LEFT OUTER JOIN LifeSciences_Classification ON LifeSciences_Agreement.ClassificationID = LifeSciences_Classification.ClassificationID LEFT OUTER JOIN LifeSciences_Company ON LifeSciences_Agreement_Company.CompanyID = LifeSciences_Company.CompanyID LEFT OUTER JOIN LifeSciences_Country ON LifeSciences_Agreement.CountryID = LifeSciences_Country.CountryID LEFT OUTER JOIN LifeSciences_Decision ON LifeSciences_Agreement.DecisionID = LifeSciences_Decision.DecisionID LEFT OUTER JOIN LifeSciences_Indication ON LifeSciences_Agreement.IndicationID = LifeSciences_Indication.IndicationID LEFT OUTER JOIN LifeSciences_Payer ON LifeSciences_Agreement.PayerID = LifeSciences_Payer.PayerID LEFT OUTER JOIN LifeSciences_RegistryRequirement ON LifeSciences_Agreement.RegistryRequirementID = LifeSciences_RegistryRequirement.RegistryRequirementID LEFT OUTER JOIN LifeSciences_RegistryStatus ON LifeSciences_Agreement.RegistryStatusID = LifeSciences_RegistryStatus.RegistryStatusID LEFT OUTER JOIN LifeSciences_TherapeuticArea ON LifeSciences_Agreement.TherapeuticAreaID = LifeSciences_TherapeuticArea.TherapeuticAreaID LEFT OUTER JOIN LifeSciences_Type ON LifeSciences_Agreement.TypeID = LifeSciences_Type.TypeID");
                this.Session["Agreements"] = myDataTable;
                return myDataTable;
            }
        }
protected void DownloadPDF_Click(object sender, ImageClickEventArgs e)
       {
           isPdfExport = true;
           /*TO PRINT ALL THE COLUMNS THAT ARE NOT VISIBLE ON THE GRID -- NOT WORKING RUNNING INTO RUN TIME ERRORS*/
                     
           RadGrid2.Rebind();
           foreach (GridColumn col in RadGrid2.MasterTableView.RenderColumns)
           {
               col.Visible = true;
           }
           GetSelectedRows();
           if (arrayList.Count > 0)
           {
               DataTable newTable = dtTable.Copy();
               foreach (DataRow row in dtTable.Rows)
               {
                   int AgreementId = (int)row["AgreementId"];
                   if (!arrayList.Contains(Convert.ToString(AgreementId)))
                   {
                       DataRow[] drRows = newTable.Select(string.Format("AgreementId = {0}", AgreementId));
                       if (drRows != null)
                       {
                           newTable.Rows.Remove(drRows[0]);
                           newTable.AcceptChanges();
                       }
                   }
               }
                 
                          RadGrid2.DataSource = newTable;
               RadGrid2.Rebind();
           }
                     foreach (GridDataItem item in RadGrid2.MasterTableView.Items)
           {
               if (!item.Selected)
                   item.Visible = false;
           }
                    foreach (GridItem commandItem in this.RadGrid2.MasterTableView.GetItems(GridItemType.CommandItem))
           {
               commandItem.Visible = false;
           }
             
             RadGrid2.MasterTableView.ExportToPdf();
             
       }
protected void GetSelectedRows()
        {
            SessionToArrayList();
  
            foreach (GridDataItem item in RadGrid1.Items)
            {
                string accountkey = item.KeyValues.Replace("{AgreementID:", "");
                accountkey = accountkey.Replace("}", "");
                accountkey = accountkey.Remove(0, 1);
                accountkey = accountkey.Remove(accountkey.Length - 1, 1);
                string AgreementId = accountkey;
  
                if (item.Selected)
                {
                    if (!arrayList.Contains(AgreementId))
                    {
                        arrayList.Add(AgreementId);
                    }
                }
                else
                {
                    if (arrayList.Contains(AgreementId))
                    {
                        arrayList.Remove(AgreementId);
                    }
                }
            }
  
            Session["selectedRows"] = arrayList;
        }
  
        protected void ReSelectedRows()
        {
            foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
            {
                string accountkey = item.KeyValues.Replace("{AgreementID:", "");
                accountkey = accountkey.Replace("}", "");
                accountkey = accountkey.Remove(0, 1);
                accountkey = accountkey.Remove(accountkey.Length - 1, 1);
                string AgreementId = accountkey;
  
                if (arrayList.Contains(AgreementId))
                {
                    item.Selected = true;
                }
            }
        }
protected void RadGrid2_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            RadGrid2.DataSource = dtTable; //need this for pdfexport
           
        }
              protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            RadGrid1.DataSource = dtTable; //need this for pdfexport
                   
  
protected void RadGrid2_DataBound(object sender, EventArgs e)
        {
            ReSelectedRows();
        }
  
        protected void RadGrid1_DataBound(object sender, EventArgs e)
        {
            ReSelectedRows();
       }  
 protected void RadGrid1_PageIndexChanged(object sender, GridPageChangedEventArgs e)
        {
            GetSelectedRows();
        }
       
        protected void SessionToArrayList()
        {
            if (Session["selectedRows"] != null)
            {
                arrayList = (ArrayList)Session["selectedRows"];
            }
        }
protected void Page_Load(object sender, EventArgs e)
       {
           if (!IsPostBack)
           {
               arrayList.Clear();
               dtTable = Agreements;
           }
       }
<telerik:RadGrid ID="RadGrid1" runat="server" CellSpacing="4"
            AllowMultiRowSelection="True" AllowFilteringByColumn="True"
           AllowAutomaticUpdates="True" AllowAutomaticInserts="True" AllowAutomaticDeletes="True" 
            GridLines="Both" OnPreRender="RadGrid1_PreRender"   
           OnItemInserted="RadGrid1_ItemInserted" OnItemUpdated="RadGrid1_ItemUpdated" OnNeedDataSource="RadGrid1_NeedDataSource"
            AutoGenerateColumns="False"  OnItemDeleted="RadGrid1_ItemDeleted" OnDataBound="RadGrid1_DataBound"
           AllowPaging="True" PageSize="15"  OnItemDataBound="RadGrid1_ItemDataBound" OnItemCreated="RadGrid1_ItemCreated"
           OnItemCommand="RadGrid1_ItemCommand" AllowSorting="True" Skin="Default" 
           >
           <%--3399FF--%>
           <ClientSettings EnableRowHoverStyle="False"> <%--EnablePostBackOnRowClick="true"--%>
           <Selecting CellSelectionMode="None" AllowRowSelect="True" ></Selecting>
           </ClientSettings>
            
            <ExportSettings IgnorePaging="True" OpenInNewWindow="True" HideStructureColumns="True" ExportOnlyData="True">
                  
           <Pdf PageHeight="210mm" PageWidth="297mm" PageTitle="Risk Sharing Agreement List" DefaultFontFamily="Arial Unicode MS"
               PageBottomMargin="20mm" PageTopMargin="20mm" PageLeftMargin="20mm" PageRightMargin="20mm" />
       </ExportSettings>
           <MasterTableView DataKeyNames="AgreementID" UseAllDataFields="True"
                            CommandItemDisplay="Top" >
                       <CommandItemSettings  ShowExportToExcelButton="False"
                            ShowRefreshButton="False" ShowAddNewRecordButton="False" />
  
                       <CommandItemTemplate>
                           <table width="100%" border="0">
                               <tr>
                               <%--    <td colspan="9">
                           <telerik:RadToolBar runat="server" ID="RadToolBar1" OnButtonClick="RadToolBar1_ButtonClick" Height="30">
                               <Items>
                                   <%--<telerik:RadToolBarButton Text="Apply filter" CommandName="FilterRadGrid" ImageUrl="~/Images/Filter.gif"
                                       ImagePosition="Right" Height="30" />
                                     
                                  <telerik:RadToolBarButton runat="server" Text="Add new record" CommandName="InitInsert" ImageUrl="~/Images/AddRecord.gif"></telerik:RadToolBarButton>         
    
                               </Items>
                     
                           </telerik:RadToolBar>
                                         
                            
                           </td>--%>
                           <td align="right">
                               <asp:ImageButton ID="DownloadPDF" runat="server" CommandName="ExportToPdf" ImageUrl="~/Images/pdf.png" OnClick="DownloadPDF_Click" /> 
                                 
                        <%--       <asp:ImageButton ID="prntBtn" OnClick="prntBtn_Click" runat="server"  ImageUrl="~/Images/printicon.jpg" Width="30" Height="30" AlternateText="Print Grid Results"
                                  OnClientClick="PrintSelectedRecord(); return false;"  />--%>
                                          
                           <asp:ImageButton ID="btnExport"  BorderStyle="None" runat="server" AlternateText="Export To Excel" CommandName="ExportToExcel" ImageUrl="~/Images/excel.png"/>            
              
<div>
     <%-- need this to export to pdf--%>
     <telerik:RadGrid runat="server" Visible="False" ID="RadGrid2" OnDataBound="RadGrid2_DataBound" OnNeedDataSource="RadGrid2_NeedDataSource">
         <ExportSettings IgnorePaging="True" OpenInNewWindow="True" HideStructureColumns="True" ExportOnlyData="True" >
               
             <Pdf PageHeight="210mm" PageWidth="297mm" PageTitle="Risk Sharing Agreement List" DefaultFontFamily="Arial Unicode MS"
          PageBottomMargin="20mm" PageTopMargin="20mm" PageLeftMargin="20mm" PageRightMargin="20mm" />
          </ExportSettings>
            
          <MasterTableView DataKeyNames="AgreementID" UseAllDataFields="True" CommandItemDisplay="Top" >
              <CommandItemSettings  ShowExportToExcelButton="False" ShowRefreshButton="False" ShowAddNewRecordButton="False" />
                
              <Columns>
                <telerik:GridTemplateColumn>
                    <HeaderTemplate>
                        <asp:Label ID="lbleditagreement" style="color: #E87722;font-size: 14;font-weight: bold" runat="server" Text="Viewing Agreement:"></asp:Label
                        <asp:Label style="color: #B1B3B3;font-size: 12;font-weight: bold" ID="lblheader" runat="server" OnLoad="litheader_load" ></asp:Label>
                        <hr style="width:100%; height: 6px; color: #EAAA00"/> 
                    </HeaderTemplate>
                      
                    <ItemTemplate>
                        <table id="Table2" cellspacing="5" cellpadding="1"  border="1" width="100%">
                          <tr>
                          <td> <!--first outer column-->
                                  <table id="Table3" cellspacing="5" cellpadding="1" width="100%" border="1">                
                                      <tr>
                                    
                                          <td align="right" class="columnHeading">
                                              Country:
                                          </td>
                                          <td>
                                              <asp:Label ID="CountryLabel" runat="server" Text='<%# Bind("Country") %>' />
                                           </td>
                                      </tr>
                                       <tr>
                                          <td align="right" class="columnHeading">  
                                              Brand Name:
                                          </td>
                                          <td>
                                               <asp:Label ID="BrandNameLabel" runat="server" Text='<%# Bind("BrandName") %>' />
                                               
                                          </td>
                                          </tr>
0
Daniel
Telerik team
answered on 06 Jun 2012, 01:12 PM
Hi Muhammad,

i attached the latest demo from our conversation to this ticket. I hope it will be helpful for the community.

Regards,
Daniel
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
Tags
Grid
Asked by
bradley baker
Top achievements
Rank 1
Answers by
Todd Anglin
Top achievements
Rank 2
bradley baker
Top achievements
Rank 1
MUHAMMAD
Top achievements
Rank 1
Daniel
Telerik team
Share this question
or