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

Radgrid with print, copy, export etc. capabillity

10 Answers 204 Views
Grid
This is a migrated thread and some comments may be shown as answers.
small_steps
Top achievements
Rank 1
small_steps asked on 11 Oct 2013, 10:16 AM

Hi all,

I have a number of grids in my project(s).  In many cases it is neccessary/helpful for users to 

  • print the grids' content
  • copy to clipbord (for further analysis in e.g. Excel)
  • export data to a Excel readable file or PDF

I have set my sights on creating a user control containing a Radgrid (of course) and a toolbar of some sort which buttons can be enabled/disabled as needed (see attached mock-up picture where the toolbar replaces a pager's fuctionality plus has some tools).  I have the feeling that this feature can be valuable to many users as it would provide a uniform approach to these common tasks.

I have be searching the forum for ideas and code snippets for my (dream) user control and I am stuck at the first stage.  The print instructions in http://www.telerik.com/community/code-library/aspnet-ajax/grid/print-radgrid-contents.aspx do not work right out of the box (with or without skins).

I suspect that I am not the first one to have abovementioned need.  Perhaps this functionality can already be found in some code library I have not stumbled on yet.  But anyway... please point out to me the resources (complete code, snippets, problems) and might help me realize my user control.

Thank you!   

10 Answers, 1 is accepted

Sort by
0
Kostadin
Telerik team
answered on 16 Oct 2013, 06:10 AM
Hi,

The approach which you are trying to implement in you UserControl is applicable only when exporting to PDF. Could you please elaborate more on your scenario? Providing us with more detailed information on the issue which you are facing might help us to pinpoint the reason for the unwanted behavior. I would also ask you to send us a small runnable sample in order to investigate the issue locally. Additionally I would suggest you to use a pager template in order to customize the paging then using a toolbar. The following help article demonstrates how to achieve that.

Regards,
Kostadin
Telerik
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 the blog feed now.
0
small_steps
Top achievements
Rank 1
answered on 18 Oct 2013, 12:04 PM
Hi Kostadin.

In essense I am trying to make a reusable grid component (user control) I can use in my projects.  Generally I would like to enable the users to export to common formats (Excel, PDF) for further work, storage or printing (hard copy).  Furthermore I need to add, delete and edit records in the databases.  All of these are included in your CommandItemSettings.  As my working languge is not English I need to translate a few display texts (sorting, pager etc.) and keep those in my reusable grid component to circumvent code duplication and tedious work.  And I need more custom functions in my component. 

I have therefore concluded that a toolbar embedded within the grid would be the most flexible solution. I have found a few samples http://www.telerik.com/help/aspnet-ajax/grid-commanditem-default-behavior.html http://www.telerik.com/community/code-library/aspnet-ajax/general/export-radgrid-content-to-excel-word-csv-pdf-with-ajax-enabled.aspx
 and below is my extraction from these samples.  It contains a lowered toolbar with three buttons and a grid (without the language stuff).  This is a regular ASPX (not the user control's ASCX).

The problem sofar is that I can not get ExportToExcel button to work.  It removes the paging from the grid but does not produce any output.  What is wrong?
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<head runat="server">
    <title></title>
    <style type="text/css">
        .smallToolBar .rtbOuter
        {
            display: block !important;
            border: 0 !important;
            border-top: solid 1px rgb(197,197,197) !important;
            padding-bottom: 1px !important;
        }
        .smallToolBar .rtbMiddle
        {
            display: block !important;
            border: 0 !important;
        }
        .smallToolBar .rtbInner {
            padding: 0 !important;
        }
        .smallToolBar .rtbItem {
            margin: 0 3px 0 3px !important;
            height: 20px !important;
        }
        .smallToolBar .rtbWrap,
        .smallToolBar .rtbOut {
            height: 20px !important;
            width: 20px !important;
        }
       .smallToolBar .rtbIcon {
            padding: 0px 0px 2px 0px !important;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
            <Scripts>
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
            </Scripts>
        </telerik:RadScriptManager>
 
        <script type="text/javascript">
            function onToolBarClientButtonClicking(sender, args) {
                var button = args.get_item();
                switch (button.get_commandName()) {
                    case "DeleteSelected":
                        args.set_cancel(!confirm('Delete all selected customers?'));
                        break;
                    case "Export":
                        args.EnableAjax = false;
                        break;
                }
            }
        </script>
     
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="RadGrid1">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="RadGrid1"></telerik:AjaxUpdatedControl>
                        <telerik:AjaxUpdatedControl ControlID="Label1"></telerik:AjaxUpdatedControl>
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
        </telerik:RadAjaxManager>
 
        <div>
            <asp:Label ID="Label1" runat="server"
                EnableViewState="False" Font-Bold="True" ForeColor="#FF8080">
            </asp:Label>
        </div>
 
        <telerik:RadGrid ID="RadGrid1" runat="server" Width="97%"
                AutoGenerateColumns="true"
                AllowSorting="True"
                AllowAutomaticUpdates="true"
                AllowAutomaticDeletes="true"
                AllowMultiRowSelection="True"
                AllowMultiRowEdit="True"
                AllowPaging="True"
                PageSize="7"
                GridLines="None"
                DataSourceID="SqlDataSource1"
                HorizontalAlign="NotSet"
                OnItemCreated="RadGrid1_ItemCreated"
                OnItemDeleted="RadGrid1_ItemDeleted"
                OnItemUpdated="RadGrid1_ItemUpdated"
                OnItemInserted="RadGrid1_ItemInserted" >
            <PagerStyle Mode="NextPrevAndNumeric"></PagerStyle>
            <MasterTableView Width="100%"
                GridLines="None"
                CommandItemDisplay="Top"
                DataSourceID="SqlDataSource1"
                EditMode="InPlace"
                HorizontalAlign="NotSet"
                DataKeyNames="CustomerID"
                AllowAutomaticInserts="True">
                <CommandItemTemplate>
                    <telerik:RadToolBar ID="RadToolBar1" runat="server" CssClass="smallToolBar"
                        OnClientButtonClicking="onToolBarClientButtonClicking"
                        AutoPostBack="true">
                        <Items>
                            <telerik:RadToolBarButton Tooltip="Add new" Text=""
                                CommandName="InitInsert"
                                ImageUrl="~/Images/add.ico"
                                Visible='<%# Not RadGrid1.MasterTableView.IsItemInserted %>'>
                            </telerik:RadToolBarButton>
                            <telerik:RadToolBarButton Tooltip="Add this Customer" Text=""
                                CommandName="PerformInsert"
                                ImageUrl="~/Images/insert.ico"
                                Visible='<%# RadGrid1.MasterTableView.IsItemInserted %>'>
                            </telerik:RadToolBarButton>
                            <telerik:RadToolBarButton Tooltip="Export to Excel" Text=""
                                CommandName="Export"
                                ImageUrl="~/Images/excel.ico">
                            </telerik:RadToolBarButton>
                        </Items>
                    </telerik:RadToolBar>
                </CommandItemTemplate>
            </MasterTableView>
            <ClientSettings>
                <Selecting AllowRowSelect="True" EnableDragToSelectRows="True"></Selecting>
            </ClientSettings>
            <ExportSettings exportonlydata="True" ignorepaging="True"
                openinnewwindow="True">
                <Pdf PageTitle="" PaperSize="A4" allowcopy="True"
                    PageBottomMargin="20mm" PageTopMargin="20mm"
                    PageLeftMargin="20mm" PageRightMargin="20mm" />
                <Excel Format="ExcelML" />
            </ExportSettings>
        </telerik:RadGrid>
     
        <asp:AccessDataSource runat="server" ID="SqlDataSource1"
            DataFile="~/App_LocalResources/Nwind.mdb"
            DeleteCommand="DELETE FROM [Customers] WHERE [CustomerID] = @CustomerID"
            InsertCommand="INSERT INTO [Customers] ([CustomerID], [CompanyName], [ContactName], [ContactTitle]) VALUES (@CustomerID, @CompanyName, @ContactName, @ContactTitle)"
            SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle] FROM [Customers]"
            UpdateCommand="UPDATE [Customers] SET [CompanyName] = @CompanyName, [ContactName] = @ContactName, [ContactTitle] = @ContactTitle WHERE [CustomerID] = @CustomerID">
            <DeleteParameters>
                <asp:Parameter Name="CustomerID" Type="String"></asp:Parameter>
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="CustomerID" Type="String"></asp:Parameter>
                <asp:Parameter Name="CompanyName" Type="String"></asp:Parameter>
                <asp:Parameter Name="ContactName" Type="String"></asp:Parameter>
                <asp:Parameter Name="ContactTitle" Type="String"></asp:Parameter>
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="CompanyName" Type="String"></asp:Parameter>
                <asp:Parameter Name="ContactName" Type="String"></asp:Parameter>
                <asp:Parameter Name="ContactTitle" Type="String"></asp:Parameter>
                <asp:Parameter Name="CustomerID" Type="String"></asp:Parameter>
            </UpdateParameters>
        </asp:AccessDataSource>       
    </div>                 
    </form>
</body>
</html>

Imports Telerik.Web.UI
Imports System.Drawing
 
Partial Class Default2
    Inherits System.Web.UI.Page
 
    Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As GridItemEventArgs)
        TryCast(RadGrid1.MasterTableView.AutoGeneratedColumns(0), GridBoundColumn).MaxLength = 5
        Dim item As GridEditableItem = TryCast(e.Item, GridEditableItem)
        If item IsNot Nothing AndAlso e.Item.IsInEditMode AndAlso e.Item.ItemIndex <> -1 Then
            TryCast(item.EditManager.GetColumnEditor("CustomerID").ContainerControl.Controls(0), TextBox).Enabled = False
        End If
    End Sub
    Protected Sub RadGrid1_ItemDeleted(ByVal source As Object, ByVal e As Telerik.Web.UI.GridDeletedEventArgs) Handles RadGrid1.ItemDeleted
        If Not e.Exception Is Nothing Then
            e.ExceptionHandled = True
            DisplayMessage(True, "Customer " + e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("CustomerID").ToString() + " cannot be deleted.")
        Else
            DisplayMessage(False, "Customer " + e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("CustomerID").ToString() + " deleted")
        End If
    End Sub
    Protected Sub RadGrid1_ItemUpdated(ByVal source As Object, ByVal e As Telerik.Web.UI.GridUpdatedEventArgs) Handles RadGrid1.ItemUpdated
        If Not e.Exception Is Nothing Then
            e.KeepInEditMode = True
            e.ExceptionHandled = True
            DisplayMessage(True, "Customer " + e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("CustomerID").ToString() + " cannot be updated due to invalid data.")
        Else
            DisplayMessage(False, "Customer " + e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("CustomerID").ToString() + " updated")
        End If
    End Sub
    Protected Sub RadGrid1_ItemInserted(ByVal source As Object, ByVal e As Telerik.Web.UI.GridInsertedEventArgs) Handles RadGrid1.ItemInserted
        If Not e.Exception Is Nothing Then
            e.ExceptionHandled = True
            e.KeepInInsertMode = True
            DisplayMessage(True, "Customer cannot be inserted due to invalid data.")
        Else
            DisplayMessage(False, "Customer inserted")
        End If
    End Sub
    Protected Sub RadGrid1_ItemCommand(ByVal source As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand
        Select Case e.CommandName
            Case "DeleteSelected"
                If RadGrid1.SelectedIndexes.Count <> 0 Then
                    For Each item As GridDataItem In RadGrid1.SelectedItems
                        e.Item.OwnerTableView.PerformDelete(item, True)
                    Next
                    e.Item.OwnerTableView.Rebind()
                End If
            Case "Export"
                RadGrid1.MasterTableView.ExportToExcel()
        End Select
    End Sub
    Private Sub DisplayMessage(ByVal isError As Boolean, ByVal text As String)
        Me.Label1.Font.Bold = True
        Me.Label1.Visible = True
        If (isError) Then
            Me.Label1.ForeColor = Color.Red
        Else
            Me.Label1.ForeColor = Color.Green
        End If
        Me.Label1.Text = text
    End Sub
End Class




0
Kostadin
Telerik team
answered on 23 Oct 2013, 07:50 AM
Hello,

Note that the export feature works only with a regular postback and you have to disable the ajax before exporting the grid. Additional information and available solutions could be found at the following help article, under Export from AJAX-enabled RadGrid section.

I hope this information proves helpful.

Regards,
Kostadin
Telerik
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 the blog feed now.
0
small_steps
Top achievements
Rank 1
answered on 23 Oct 2013, 12:30 PM
Hi Kostadin.

In my source code above I have this script:
function onToolBarClientButtonClicking(sender, args) {
  var button = args.get_item();
  switch (button.get_commandName()) {
      case "DeleteSelected":
          args.set_cancel(!confirm('Delete all selected customers?'));
          break;
      case "Export":
          args.EnableAjax = false;
          break;
  }
}
The client-side event fires OK and EnableAJAX is changed to FALSE.

On the server-side I receive the ItemCommand event with CommandName="Export" so ExportToExcel is called. 
Protected Sub RadGrid1_ItemCommand(ByVal source As Object, _
        ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand
    Select Case e.CommandName
        Case "DeleteSelected"
            If RadGrid1.SelectedIndexes.Count <> 0 Then
                For Each item As GridDataItem In RadGrid1.SelectedItems
                    e.Item.OwnerTableView.PerformDelete(item, True)
                Next
                e.Item.OwnerTableView.Rebind()
            End If
        Case "Export"
            RadGrid1.MasterTableView.ExportToExcel()
    End Select
End Sub

So clicking the Export button on the grid's embedded toolbar results in

  • the grid is refreshed without the toolbar
  • the grid is without paging
  • I get no Excel document

What am I missing?

 

 

0
small_steps
Top achievements
Rank 1
answered on 23 Oct 2013, 03:20 PM
Hi Kostadin.

As you have twice referred to me the same article (Export from AJAX-enabled RadGrid) I want to underline what I am trying to do.  Please look at the attached picture (similar to the one in my first post).  I need grid with a toolbar (or closely associated to a grid) similar to Telerik's implementation of "commandbar" (CommandItemDisplay="top").  I need to add my own commands / shortcuts as normally on toolbars.  And I would like to place the grid's title to the left on this toolbar.

Posting some code to reproduce the functionality of your "commandbar" would help. 
0
Kostadin
Telerik team
answered on 28 Oct 2013, 08:30 AM
Hello,

In order to disable the ajax you have to wire the OnRequestStart event of the ajax manager, determine whether the target control is ajaxified and explicitly disable its ajax mode to export with regular postback.
function onRequestStart(sender, args) {
  if (args.get_eventTarget().indexOf("ExportButtonID") >= 0)
    args.set_enableAjax(false);
}

As to the question related with the CommandItemTemplate you could check out the following live example.

Regards,
Kostadin
Telerik
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 the blog feed now.
0
small_steps
Top achievements
Rank 1
answered on 28 Oct 2013, 03:02 PM
Hi, Kostadin.

I still do not get it. 

Clicking the Export button on the grid's embedded toolbar results in

  • On the client side: onToolBarClientButtonClicking is called, onRequestStart is NOT
  • On the server side:  RadGrid1_ItemCommand is called
  • the grid is refreshed without the toolbar and without paging
  • I get no Excel document

 

Please CORRECT my runnable source below to get export to work by clicking the toolbar button.
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default4.aspx.vb" Inherits="Default4" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
 
<!DOCTYPE>
 
<html>
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
            <Scripts>
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
            </Scripts>
        </telerik:RadScriptManager>
 
        <script type="text/javascript">
            function onToolBarClientButtonClicking(sender, args) {
                var button = args.get_item();
                var nam = args.get_item().get_commandName();
                switch (nam) {
                    case "ExportExcel":
                        alert("onToolBarClientButtonClicking: args.EnableAjax = false");
                        args.EnableAjax = false;
                        break;
                }
            }
            function onRequestStart(sender, args) {
                if (args.get_eventTarget().indexOf("Export") >= 0) {
                    alert("onRequestStart: args.EnableAjax = false");
                    args.set_enableAjax(false);
                }
            }
        </script>
     
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <ClientEvents OnRequestStart="onRequestStart"></ClientEvents>
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="RadGrid1">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="RadGrid1"></telerik:AjaxUpdatedControl>
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
        </telerik:RadAjaxManager>
 
        <telerik:RadGrid ID="RadGrid1" runat="server" Width="97%"
                AllowPaging="True" PageSize="7" DataSourceID="SqlDataSource1">
            <MasterTableView Width="100%" CommandItemDisplay="top">
                <CommandItemTemplate>
                    <telerik:RadToolBar ID="RadToolBar1" runat="server"
                        OnClientButtonClicking="onToolBarClientButtonClicking"
                        AutoPostBack="true">
                        <Items>
                            <telerik:RadToolBarButton Tooltip="Export to Excel"
                                CommandName="ExportExcel" Text="Export">
                            </telerik:RadToolBarButton>
                        </Items>
                    </telerik:RadToolBar>
                </CommandItemTemplate>
            </MasterTableView>
            <ExportSettings exportonlydata="True" ignorepaging="True"
                openinnewwindow="True">
                <Excel Format="ExcelML" />
            </ExportSettings>
        </telerik:RadGrid>
     
        <asp:AccessDataSource runat="server" ID="SqlDataSource1" DataFile="~/App_LocalResources/Nwind.mdb"
            SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle] FROM [Customers]" >        </asp:AccessDataSource>       
    </div>                 
    </form>
</body>
</html>
 
CODE BEHIND:
Imports Telerik.Web.UI
Imports System.Drawing
 
Partial Class Default4
    Inherits System.Web.UI.Page
 
    Protected Sub RadGrid1_ItemCommand(ByVal source As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand
        Select Case e.CommandName
            Case "ExportExcel"
                RadGrid1.MasterTableView.ExportToExcel()
        End Select
    End Sub
End Class

Thanks in advance.
0
Kostadin
Telerik team
answered on 31 Oct 2013, 08:27 AM
Hi,

If you debugged your sample you will noticed that the event target is not the RadToolBarButton, but it is the RadToolBar itself. So you could use the following code snippet.
function onRequestStart(sender, args) {
     if (args.get_eventTarget().indexOf("RadToolBar1") >= 0) {
         alert("onRequestStart: args.EnableAjax = false");
         args.set_enableAjax(false);
     }
 }

Keep in mind that no matter which button you clicked inside the ToolBar the ajax will be disabled. If you want to disable the ajax only when you click the export button then you could use the following approach.
JavaScript:
<script type="text/javascript">
 
    function disableAjax(sender, args) {
        if (args.get_item().get_commandName() == "ExportExcel") {
            var ajaxPanel = $find("<%= RadAjaxManager1.ClientID %>");
            ajaxPanel.set_enableAJAX(false)
        }
    }
</script>
Mark-up:
<CommandItemTemplate>
     <telerik:RadToolBar ID="RadToolBar1" runat="server" OnClientButtonClicked="disableAjax"
         AutoPostBack="true">
         <Items>
             <telerik:RadToolBarButton ToolTip="Export to Excel"
                 CommandName="ExportExcel" Text="Export">
             </telerik:RadToolBarButton>
         </Items>
     </telerik:RadToolBar>
 </CommandItemTemplate>

Additionally I prepared a small sample based on the provided code and attached it to this forum thread.

Regards,
Kostadin
Telerik
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 the blog feed now.
0
John
Top achievements
Rank 1
answered on 23 Apr 2015, 03:29 PM

Hello,

I am just getting started with Telerik.  But I wanted to do exactly as the original post - I wanted to have these generic types of features for all of my grids.   I was wondering what is the recommended approach?  Is it a user control or a custom grid (inheriting from RadGrid).  I was just wanted to get the most reuse and conformity as possible.

Thanks in advance.

0
Kostadin
Telerik team
answered on 28 Apr 2015, 08:40 AM
Hi John,

It depends whether you need to modify only the grid or you want to use another controls with it. For the first case you can create a custom class which inherits RadGrid and for the second scenario is suitable to use a UserControl. Keep in mind that both approaches are valid so it depends on your scenario.

Regards,
Kostadin
Telerik
 

See What's Next in App Development. Register for TelerikNEXT.

 
Tags
Grid
Asked by
small_steps
Top achievements
Rank 1
Answers by
Kostadin
Telerik team
small_steps
Top achievements
Rank 1
John
Top achievements
Rank 1
Share this question
or