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

Export to CSV loads data when the RadGrid has no

4 Answers 191 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Sriram
Top achievements
Rank 1
Sriram asked on 07 Aug 2014, 11:21 AM
Hi,

I have a web form with Master page enabled in it. The web form has list of search criteria (Telerik controls only) and choosing them and giving a search gives the results in the RadGrid (This grid has Export to Excel & Export to CSV enabled). What happens is, when the page is loaded the grid is displayed without any data (I am simply binding to RadGridActiveInquiry.DataSource = new object[] { };

But what happens is, if  click on Export to Excel or Export to CSV, the excel is opened with data though the grid is not bound to the same data. I am not sure how it is happening. I have put break point and was debugging. As soon as I click on the CSV / Excel icon at the top right of the grid, it is loading the data. If I give normal search based on the filter criteria and fire CSV / Excel the fitlered data gets populated in the excel. In the first load of the page it self the CSV & Excel export is not working as expected. 

I have given my code below.

<%@ Page Title="" Language="C#" MasterPageFile="~/Templates/OneColumn.Master" AutoEventWireup="true"
    CodeBehind="ActiveInquiry.aspx.cs" Inherits="ABS2.Customer.ActiveInquiry" ValidateRequest="false" ClientIDMode="AutoID" %>

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <link href="../CSS/CustomerActionMenu.css" rel="stylesheet" type="text/css" />

    <telerik:radscriptblock id="RadScriptBlockActiveInquiry" runat="server">
<script type="text/javascript">
   ActiveInquiry = {
openStatusChangePopup: function () {
           var selectedIDs = GetSelectedIDs();
           PopupWindow.open('/customer/popups/CustomerStatusChangeDialog.aspx?CustIDS=' + selectedIDs, 700, 600, ActiveInquiry.refreshGrid);
           return false;
       },
openCopyPopup: function () {
           var selectedIDs = GetSelectedIDs();
           PopupWindow.open('/Customer/Popups/CustomerCopy.aspx?CustIDS=' + selectedIDs, 700, 600);
           return false;
       },
openTransferPopup: function () {
           var selectedIDs = GetSelectedIDs();
           PopupWindow.open('/Customer/Popups/CustomerTransfer.aspx?CustIDS=' + selectedIDs, 700, 600, ActiveInquiry.refreshGrid);
           return false;
       },
onRequestStart: function (sender, args) {
           if (args.get_eventTarget().indexOf("ExportToExcelButton") >= 0 ||
               args.get_eventTarget().indexOf("ExportToWordButton") >= 0 ||
               args.get_eventTarget().indexOf("ExportToCsvButton") >= 0 ||
               args.get_eventTarget().indexOf("ExportToPdfButton") >= 0) {
               args.set_enableAjax(false);
           }
       },
refreshGrid: function () {
           $find("<%= RadAjaxManager.GetCurrent(Page).ClientID %>").ajaxRequest("RebindGrid");
       },
    showHideGroupAction: function () {
           var grid = $find("<%=RadGridActiveInquiry.ClientID %>");
           var table = document.getElementById("<%=TableMegaDropdown.ClientID %>");
           var gridSelectedItems = grid.get_masterTableView().get_selectedItems();
           table.style.display = gridSelectedItems.length > 0 ? "block" : "none";
       }
   };

            function ShowSoloForm(id, action) {
                switch (action) {
                    case 'Status':
                        PopupWindow.open('/customer/popups/CustomerStatusChangeDialog.aspx?CustomerID=' + id, 700, 400, ActiveInquiry.refreshGrid);
                        break;
                    case 'Transfer':
                        PopupWindow.open('/Customer/Popups/CustomerTransfer.aspx?CustIDS=' + id, 600, 400, ActiveInquiry.refreshGrid);
                        break;
                    case 'Copy':
                        PopupWindow.open('/Customer/Popups/CustomerCopy.aspx?CustIDS=' + id, 700, 400);
                        break;
                    default:
                        break;
                }

                return false;
   }

   function GetSelectedIDs() {
       var selectedIDs = '';
       var selectedItems = $find('<%= RadGridActiveInquiry.ClientID %>').get_masterTableView().get_selectedItems();
for (var ii = 0; ii < selectedItems.length; ii++) {
   selectedIDs += (selectedIDs.length > 0 ? ',' : '') + selectedItems[ii].getDataKeyValue('CustomerId');
            }
return selectedIDs;
            }

            function RadMenuCloseOnClicked() {
                var menu = $find("<%=RadMenuActionMenu.ClientID %>");
                menu.close();
            }

   function CloseRadToolTip(toolTip) {
       var radToolTip = $find(toolTip);
       if (radToolTip.isVisible()) {
           radToolTip.hide();
       }
   }

   function refreshGrid() {
       $find("<%= RadAjaxManager.GetCurrent(Page).ClientID %>").ajaxRequest("RebindGrid");
   }
</script>
</telerik:radscriptblock>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="AN" runat="server">
<table cellpadding="0" cellspacing="0" border="0" style="margin-top: 20px; margin-left: -320px;"
runat="server" id="TableMegaDropdown">
<tr>
<td>
<div id="MegaDropDown">
<script type="text/javascript">
   function itemOpened(s, e) {
       if ($telerik.isIE8) {
           // Fix an IE 8 bug that causes the list bullets to disappear (standards mode only)
           $telerik.$("li", e.get_item().get_element())
                                .each(function () { this.style.cssText = this.style.cssText; });
                            }
                        }
                    </script>
                    <telerik:radmenu runat="server" id="RadMenuActionMenu" onclientitemopened="itemOpened"
                        skin="Sitefinity" enableshadows="false" style="z-index: 2900" collapseanimation-type="None"
                        collapseanimation-duration="0" collapsedelay="0">
<Items>
<telerik:RadMenuItem PostBack="false" Width="125px">
                                 <ItemTemplate>
                                    <div class="fDiv">
                                        <asp:ImageButton ID="btnTest" runat="server" Width="128px" Height="28px" ImageUrl="<%$ Resources:UI, ActiveInquiry_ImageUrl_ImagesButtonActionNoText %>" />
                                        <div class="txtWrap">
                                           <asp:Label ID="Label2" runat="server" Text="<%$ Resources:UI, ActiveInquiry_HTML_ActionMenu %>"></asp:Label> 
                                        </div>
                                    </div>
                                </ItemTemplate>
<Items>
<telerik:RadMenuItem CssClass="Events" Width="440px">
<ItemTemplate>
<div id="EventWrapper" class="Wrapper">
<h3>
<asp:placeholder ID="Placeholder1" runat="server"><%= Resources.UI.ActiveInquiry_HTML_GroupActions %></asp:placeholder></h3>
<div class="newsLeft">
    <asp:LinkButton ID="LinkButtonTransfer" runat="server" OnClientClick="RadMenuCloseOnClicked(); return ActiveInquiry.openTransferPopup();"
                                                        Text="<%$ Resources:UI, ActiveInquiry_Text_TransferInquiries %>" /><br />
                                                    <asp:LinkButton ID="LinkButtonCopy" runat="server" OnClientClick="RadMenuCloseOnClicked(); return ActiveInquiry.openCopyPopup();"
                                                        Text="<%$ Resources:UI, ActiveInquiry_Text_CopyInquiries %>" /><br />
<asp:LinkButton ID="LinkButtonStatus" runat="server" OnClientClick="RadMenuCloseOnClicked(); return ActiveInquiry.openStatusChangePopup();"
                                                        CommandName="Status"><%= Resources.UI.ActiveInquiry_HTML_UpdateStatus %></asp:LinkButton><br />
<asp:Label ID="LabelNoAction" runat="server" Text="" Visible="false" /><br />
<asp:Label ID="LabelNoEmployees" runat="server" Text="" Visible="false" />
<div style="height: 10px;">
</div>
</div>
</div>
</ItemTemplate>
</telerik:RadMenuItem>
</Items>
</telerik:RadMenuItem>
</Items>
</telerik:radmenu>
                </div>
            </td>
        </tr>
    </table>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MC" runat="server">
    <div id="divContainer" runat="server">
        <telerik:radajaxmanagerproxy id="RadAjaxManagerProxyCustomerSearch" runat="server">
   <AjaxSettings>
   <telerik:AjaxSetting AjaxControlID="RadButtonSearch">
   <UpdatedControls>
   <telerik:AjaxUpdatedControl ControlID="RadGridActiveInquiry" />
   </UpdatedControls>
   </telerik:AjaxSetting>
                <telerik:AjaxSetting AjaxControlID="RadGridActiveInquiry">
   <UpdatedControls>
   <telerik:AjaxUpdatedControl ControlID="RadGridActiveInquiry" />
   </UpdatedControls>
   </telerik:AjaxSetting>
   </AjaxSettings>
   </telerik:radajaxmanagerproxy>
        <div style="margin-top: -56px; margin-left: 17px; margin-right: 10px;">
            <table cellpadding="0" cellspacing="0" border="0">
                <tr>
                    <td>
                        <asp:Label ID="LabelAssignedTo" runat="server" Text="<%$ Resources:UI, ActiveInquiry_Text_LabelAssignedTo %>" SkinID="labelSearchTitle" /><br />
                        <telerik:radcombobox id="RadComboBoxInquiryAssignedTo" runat="server" width="125px" />
                    </td>
                    <td style="width: 5px;" />
                    <td valign="top" align="left">
                        <div>
                            <asp:Label ID="DateFrom" runat="server" Text="<%$ Resources:UI, ActiveInquiry_Text_DateFrom %>" SkinID="labelSearchTitle" />
                        </div>
                        <div>
                            <telerik:raddatepicker id="RadDatePickerFrom" runat="server" mindate="<%$ Resources:UI, ActiveInquiry_MinDate_RadDatePickerFrom %>">
                                <Calendar ID="Calendar2" UseRowHeadersAsSelectors="False" UseColumnHeadersAsSelectors="False" ViewSelectorText="<%$ Resources:UI, ActiveInquiry_ViewSelectorText_Calendar2 %>" runat="server">
                                    <SpecialDays>
                                        <telerik:RadCalendarDay Repeatable="Today" Date="">
                                            <ItemStyle BackColor="#FFFF99" />
                                        </telerik:RadCalendarDay>
                                    </SpecialDays>
                                </Calendar>
                                <DateInput ID="DateInput2" DateFormat="d" DisplayDateFormat="d" Width="" runat="server"></DateInput>                   
                                <DatePopupButton ImageUrl="" HoverImageUrl="" ToolTip="<%$ Resources:UI, ActiveInquiry_DatePopupButton_ToolTip %>"></DatePopupButton>
                                <ShowAnimation Duration="200" />
                            </telerik:raddatepicker>
                        </div>
                    </td>
                    <td valign="top" align="left">
                        <div>
                            <asp:Label ID="DateTo" runat="server" Text="<%$ Resources:UI, ActiveInquiry_Text_DateTo %>" SkinID="labelSearchTitle" />
                        </div>
                        <div>
                            <telerik:raddatepicker id="RadDatePickerTo" runat="server" mindate="<%$ Resources:UI, ActiveInquiry_MinDate_RadDatePickerTo %>">
                                <Calendar ID="Calendar1" UseRowHeadersAsSelectors="False" UseColumnHeadersAsSelectors="False" ViewSelectorText="<%$ Resources:UI, ActiveInquiry_ViewSelectorText_Calendar1 %>" runat="server">
                                    <SpecialDays>
                                        <telerik:RadCalendarDay Repeatable="Today" Date="">
                                            <ItemStyle BackColor="#FFFF99" />
                                        </telerik:RadCalendarDay>
                                    </SpecialDays>
                                </Calendar>
                                <DateInput ID="DateInput1" DateFormat="d" DisplayDateFormat="d" Width="" runat="server"></DateInput>                   
                                <DatePopupButton ImageUrl="" HoverImageUrl="" ToolTip="<%$ Resources:UI, ActiveInquiry_DatePopupButton_ToolTip_1 %>"></DatePopupButton>
                                <ShowAnimation Duration="200" />
                            </telerik:raddatepicker>
                        </div>
                    </td>
                    <td valign="bottom">
                        <telerik:radbutton id="RadButtonSearch" runat="server" image-imageurl="<%$ Resources:UI, ActiveInquiry_ImageUrl_RadButtonSearch %>"
                            causesvalidation="true" width="24px" height="24px" tooltip="<%$ Resources:UI, ActiveInquiry_ToolTip_Search %>" onclick="ImageSearchIcon_Click">
   </telerik:radbutton>
                        <telerik:radbutton id="RadButtonClear" runat="server" image-imageurl="<%$ Resources:UI, ActiveInquiry_ImageUrl_RadButtonClear %>"
                            width="24px" height="24px" tooltip="<%$ Resources:UI, ActiveInquiry_ToolTip_Clear %>" causesvalidation="false" autopostback="true" onclick="ClearForm_Click">
   </telerik:radbutton>
                    </td>
                </tr>
                <tr>
                    <td colspan="2"></td>
                    <td colspan="2" style="height: 14px;">
                        <asp:CompareValidator ID="CVEndDate" runat="server" ControlToCompare="RadDatePickerFrom"
                            ControlToValidate="RadDatePickerTo" ErrorMessage="<%$ Resources:UI, ActiveInquiry_ErrorMessage_EndDateMustBeGreaterThanOrEqualToStartDate %>"
                            ForeColor="Red" Operator="GreaterThanEqual"></asp:CompareValidator>
                    </td>
                </tr>
            </table>
        </div>
        <table style="width: 100%" cellpadding="0" cellspacing="0" border="0" class="leftContentBodyTopBGLG">
            <tr>
                <td>
                    <div id="toppanel">
                        <table cellpadding="0" cellspacing="0" border="0">
                            <tr>
                                <td valign="top">
                                    <div style="margin-left: 15px; margin-right: 15px; margin-top: 15px;">
                                        <telerik:radgrid id="RadGridActiveInquiry" runat="server" gridlines="None" allowpaging="true" allowsorting="true" autogeneratecolumns="false"
                                            allowmultirowselection="True" width="100%" PageSize="10"
                                            onneeddatasource="RadGridActiveInquiry_NeedDataSource" onitemcreated="RadGridActiveInquiry_ItemCreated" onitemdatabound="RadGridActiveInquiry_ItemDataBound" onitemcommand="RadGridActiveInquiry_ItemCommand">
                                            <GroupingSettings CaseSensitive="false" />
                                            <ExportSettings ExportOnlyData="false" HideStructureColumns="true" IgnorePaging="true" Excel-Format="Biff" />
                                            <PagerStyle Mode="NextPrevNumericAndAdvanced" />
                                   <MasterTableView DataKeyNames="CustomerId" CommandItemDisplay="Top" ShowHeadersWhenNoRecords="true" EnableNoRecordsTemplate="true" ClientDataKeyNames="CustomerId">
                                   <%--<NoRecordsTemplate>
                                   <div><%= Resources.UI.ActiveInquiry_HTML_NoRecordsWereReturned %></div>
                                   </NoRecordsTemplate>--%>
                                                <%--<CommandItemSettings ExportToCsvText="<%$ Resources:UI, ActiveInquiry_Text_ExportToCSV %>" ExportToExcelText="<%$ Resources:UI, ActiveInquiry_Text_ExportToExcel %>" ShowRefreshButton="false"
                                       ShowExportToExcelButton="true" ShowExportToCsvButton="true" ShowAddNewRecordButton="false" />--%>
                                                <CommandItemSettings  ShowRefreshButton="false" ShowExportToExcelButton="true" ShowExportToCsvButton="true" ShowAddNewRecordButton="false" />
                                   <RowIndicatorColumn HeaderStyle-Width="20px" />
                                   <ExpandCollapseColumn HeaderStyle-Width="20px" />
                                   <Columns>
                                                    <telerik:GridBoundColumn DataField="CustomerId" HeaderText="<%$ Resources:UI, ActiveInquiry_HeaderText_CustomerId %>" UniqueName="id" ItemStyle-VerticalAlign="Top" Display="false" Exportable="false" >
                                                        <ItemStyle VerticalAlign="Top"></ItemStyle>                                                        
                                                    </telerik:GridBoundColumn>
                                   <telerik:GridClientSelectColumn UniqueName="select" ItemStyle-VerticalAlign="Top" ItemStyle-Width="15px" HeaderStyle-Width="15px" Exportable="false" />
                                                    <telerik:GridTemplateColumn UniqueName="image" AllowFiltering="false" ItemStyle-VerticalAlign="Top" HeaderStyle-Width="43px" Exportable="false">
                                                        <ItemTemplate>
                                                            <asp:Image ID="menuIcon" runat="server" ImageUrl="<%$ Resources:UI, ActiveInquiry_ImageUrl_menuIcon %>" />
                                                            <telerik:RadToolTip ID="RadToolTip1" runat="server" TargetControlID="menuIcon" HideEvent="LeaveTargetAndToolTip"
                                                                Position="MiddleRight" Width="200px" SkinID="RadToolTipDefault" AutoCloseDelay="10000"
                                                                HideDelay="0">
                                                                <div style="margin: 15px;">
                                                                    <div style="background-color: #1FA9FF; width: 100%; text-transform: uppercase; color: White;">
                                                                        <div style="padding: 5px;">
                                                                            <asp:placeholder ID="Placeholder2" runat="server"><%= Resources.UI.ActiveInquiry_HTML_SoloActions %></asp:placeholder></div>
                                                                    </div>
                                                                    <div style="margin-left: 2px;">
                                                                        <p style="line-height: 20px;">
                                                                            <asp:LinkButton ID="LinkButtonTransfer" runat="server" CausesValidation="false" CommandName="Transfer"
                                                                            Text="<%$ Resources:UI, ActiveInquiry_Text_TransferInquiry %>" />
                                                                        </p>
                                                                        </div>
                                                                    <div style="margin-left: 2px;">
                                                                        <p style="line-height: 20px;">
                                                                            <asp:LinkButton ID="LinkButtonCopy" runat="server" CausesValidation="false" CommandName="Copy"
                                                                            Text="<%$ Resources:UI, ActiveInquiry_Text_CopyInquiry %>" />
                                                                        </p>
                                                                    </div>
                                                                    <div style="margin-left: 2px;">
                                                                        <p style="line-height: 20px;">
                                                                            <asp:LinkButton ID="LinkButtonStatus" runat="server" CommandName="Status"
                                                                                CausesValidation="false"><%= Resources.UI.ActiveInquiry_HTML_UpdateStatus_1 %></asp:LinkButton>
                                                                        </p>
                                                                    </div>
                                                                </div>
                                                            </telerik:RadToolTip>
                                                        </ItemTemplate>
                                                    </telerik:GridTemplateColumn>
                                   <telerik:GridBoundColumn DataField="DaysOpen" HeaderText="<%$ Resources:UI, ActiveInquiry_HeaderText_DaysOpen %>" UniqueName="DaysOpen" ItemStyle-Width="65px" ItemStyle-HorizontalAlign="Left">
                                                        <HeaderStyle Width="79px"></HeaderStyle>
                                                    </telerik:GridBoundColumn>
                                   <telerik:GridBoundColumn DataField="AssignedTo" HeaderText="<%$ Resources:UI, ActiveInquiry_HeaderText_AssignedTo %>" UniqueName="AssignedTo" ItemStyle-Width="90px" ItemStyle-HorizontalAlign="Left">
                                                        <HeaderStyle Width="105px"></HeaderStyle>
                                                    </telerik:GridBoundColumn>
                                                    <telerik:GridTemplateColumn HeaderText="<%$ Resources:UI, ActiveInquiry_HeaderText_ClientName %>" UniqueName="ClientName" ItemStyle-Width="70px"
   SortExpression="ClientName" ItemStyle-VerticalAlign="Top" ItemStyle-HorizontalAlign="Left">
   <ItemTemplate>
   <asp:LinkButton runat="server" ID="LinkButtonDetails" OnClick="LinkButtonDetails_Click" CausesValidation="False" />
   </ItemTemplate>
                                                        <HeaderStyle Width="85px"></HeaderStyle>
   </telerik:GridTemplateColumn>
                                   <telerik:GridBoundColumn DataField="CallerName" HeaderText="<%$ Resources:UI, ActiveInquiry_HeaderText_CallerName %>" UniqueName="CallerName" ItemStyle-Width="70px" ItemStyle-HorizontalAlign="Left">
                                                        <HeaderStyle Width="87px"></HeaderStyle>
                                                    </telerik:GridBoundColumn>
                                   <telerik:GridBoundColumn DataField="InquiryCaseType" HeaderText="<%$ Resources:UI, ActiveInquiry_HeaderText_InquiryCaseType %>" UniqueName="CaseType" ItemStyle-Width="120px" ItemStyle-HorizontalAlign="Left">
                                                        <HeaderStyle Width="131px"></HeaderStyle>
                                                    </telerik:GridBoundColumn>
                                   <telerik:GridBoundColumn DataField="SalesPerson" HeaderText="<%$ Resources:UI, ActiveInquiry_HeaderText_SalesPerson %>" UniqueName="SalesPerson" ItemStyle-Width="70px" ItemStyle-HorizontalAlign="Left">
                                                        <HeaderStyle Width="88px"></HeaderStyle>
                                                    </telerik:GridBoundColumn>
                                   <telerik:GridBoundColumn DataField="ReferralSource" HeaderText="<%$ Resources:UI, ActiveInquiry_HeaderText_ReferralSource %>" UniqueName="ReferralSource" ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Left">
                                                        <HeaderStyle Width="97px"></HeaderStyle>
                                                    </telerik:GridBoundColumn>
                                   <telerik:GridBoundColumn DataField="InquiryFollowUpDate" DataFormatString="{0:MM/dd/yyyy}" HeaderText="<%$ Resources:UI, ActiveInquiry_HeaderText_FollowUpDate %>" UniqueName="FollowUpDate" ItemStyle-Width="60px">
                                                        <HeaderStyle Width="75px"></HeaderStyle>
                                                    </telerik:GridBoundColumn>
                                   <telerik:GridBoundColumn DataField="CreatedBy" HeaderText="<%$ Resources:UI, ActiveInquiry_HeaderText_CreatedBy %>" UniqueName="CreatedBy" ItemStyle-Width="60px" ItemStyle-HorizontalAlign="Left">
                                                        <HeaderStyle Width="90px"></HeaderStyle>
                                                    </telerik:GridBoundColumn>
                                   <telerik:GridBoundColumn DataField="Zip" HeaderText="<%$ Resources:UI, ActiveInquiry_HeaderText_Zip %>" UniqueName="Zip" ItemStyle-Width="26px" ItemStyle-HorizontalAlign="Left">
                                                        <HeaderStyle Width="45px"></HeaderStyle>
                                                    </telerik:GridBoundColumn>
                                   <telerik:GridBoundColumn DataField="Status" HeaderText="<%$ Resources:UI, ActiveInquiry_HeaderText_Status %>" UniqueName="Status" ItemStyle-Width="120px" ItemStyle-HorizontalAlign="Left">
                                                        <HeaderStyle Width="132px"></HeaderStyle>
                                                    </telerik:GridBoundColumn>
                                   </Columns>
                                   </MasterTableView>
                                   <ClientSettings Scrolling-UseStaticHeaders="True" AllowDragToGroup="true" ClientEvents-OnRowSelected="ActiveInquiry.showHideGroupAction"
                                   ClientEvents-OnRowDeselected="ActiveInquiry.showHideGroupAction" ClientEvents-OnGridCreated="ActiveInquiry.showHideGroupAction">
                                   <Selecting AllowRowSelect="true" UseClientSelectColumnOnly="true" />
                                   <Scrolling UseStaticHeaders="True" />
                                   <ClientEvents OnGridCreated="ActiveInquiry.showHideGroupAction" OnRowSelected="ActiveInquiry.showHideGroupAction"
                                   OnRowDeselected="ActiveInquiry.showHideGroupAction" />
                                   </ClientSettings>
                                   <FilterMenu EnableImageSprites="False" />
                                   <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default" />
                                   </telerik:radgrid>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>
                </td>
            </tr>
        </table>        
    </div>
</asp:Content>

Code behind code is below.


using ABS2.BUSINESS;
using ABS2.COMMON;
using ABS2.ENTITY;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
//using System.Web;
//using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace ABS2.Customer
{
public partial class ActiveInquiry : ABS2.Framework.BasePage
{

        private List<cuCaseType> _cuCaseTypes;
        private List<cuStatusType> _cuStatusTypes;

        #region Init
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.PreRender += new System.EventHandler(this.ActiveInquiriesSearch_PreRender);
        }

        private void ActiveInquiriesSearch_PreRender(object sender, EventArgs e)
        {
            //if (!Page.IsPostBack)
            //{
            //    BindDropDowns();
            //    SetInitialSearchCriteria();
            //}
        }

        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            if (e.Argument == "RebindGrid")
            {
                RadGridActiveInquiry.MasterTableView.SortExpressions.Clear();
                RadGridActiveInquiry.MasterTableView.GroupByExpressions.Clear();
                RadGridActiveInquiry.Rebind();
            }
        }
        #endregion

        public void BindDropDowns()
        {
            List<int> locationIDs = SessionBO.UserLocations.Select(x => x.Key).ToList();

            List<string> officeStaffRoles = new List<string> {UtilityHelpers.GetResource("officeRoleBranchManager"),
   UtilityHelpers.GetResource("officeRoleAdministrativeAssistant"),
   UtilityHelpers.GetResource("officeRoleFranchiseOwner"),
   UtilityHelpers.GetResource("officeRoleNurseManager"),
   UtilityHelpers.GetResource("officeRoleOfficeStaff"),
   UtilityHelpers.GetResource("officeRoleStaffingCoordinator"),
                UtilityHelpers.GetResource("officeRoleSalesRep")
   };

            UtilityHelpers.PopulateDropDown(RadComboBoxInquiryAssignedTo, new EmployeeBO().GetEmployeesInOfficeRoles(locationIDs, officeStaffRoles), Constants.DROP_DOWN_SELECT_ONE, true);
            RadComboBoxInquiryAssignedTo.DropDownWidth = UtilityHelpers.RadComboBoxDropDownWidth(RadComboBoxInquiryAssignedTo);
        }

        private void SetInitialSearchCriteria()
        {
            RadComboBoxInquiryAssignedTo.SelectedValue = "-1";
            RadGridActiveInquiry.DataSource = new object[] { };
            RadGridActiveInquiry.VirtualItemCount = 0;
           // RadGridActiveInquiry.Rebind();
        }

protected void Page_Load(object sender, EventArgs e)
{
RadAjaxManager manager = RadAjaxManager.GetCurrent(Page);
            manager.ClientEvents.OnRequestStart = "ActiveInquiry.onRequestStart";
manager.AjaxRequest += new RadAjaxControl.AjaxRequestDelegate(RadAjaxManager1_AjaxRequest);
            manager.AjaxSettings.AddAjaxSetting(manager, this.RadGridActiveInquiry);
            if (!IsPostBack)
            {
                Page.Form.DefaultButton = this.RadButtonSearch.UniqueID;
            }
            RadDatePickerFrom.Culture = Thread.CurrentThread.CurrentCulture;
            RadDatePickerFrom.DateInput.DateFormat = "d";
            RadDatePickerFrom.DateInput.DisplayDateFormat = "d";
            RadDatePickerFrom.Calendar.CultureInfo = Thread.CurrentThread.CurrentCulture;
            RadDatePickerFrom.Calendar.DayCellToolTipFormat = Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern;
            RadDatePickerTo.Culture = Thread.CurrentThread.CurrentCulture;
            RadDatePickerTo.DateInput.DateFormat = "d";
            RadDatePickerTo.DateInput.DisplayDateFormat = "d";
            RadDatePickerTo.Calendar.CultureInfo = Thread.CurrentThread.CurrentCulture;
            RadDatePickerTo.Calendar.DayCellToolTipFormat = Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern;

            if (!Page.IsPostBack)
            {
                BindDropDowns();
                SetInitialSearchCriteria();
            }
        }

        protected void ImageSearchIcon_Click(object sender, EventArgs e)
        {
            RadGridActiveInquiry.Rebind();
        }

        protected void ClearForm_Click(object sender, EventArgs e)
        {
            RadComboBoxInquiryAssignedTo.SelectedValue = "-1";
            RadDatePickerFrom.SelectedDate = null;
            RadDatePickerTo.SelectedDate = null;
            RadGridActiveInquiry.DataSource = new object[] { };
            RadGridActiveInquiry.MasterTableView.SortExpressions.Clear();
            RadGridActiveInquiry.MasterTableView.GroupByExpressions.Clear();
            RadGridActiveInquiry.VirtualItemCount = 0;
            //RadGridActiveInquiry.Rebind();
        }

protected void RadGridActiveInquiry_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
            DateTime dateFrom = RadDatePickerFrom.SelectedDate == null ? DateTime.Now.AddDays(-1000) : Convert.ToDateTime(RadDatePickerFrom.SelectedDate);
            DateTime dateTo = RadDatePickerTo.SelectedDate == null ? DateTime.Now.AddDays(30) : Convert.ToDateTime(RadDatePickerTo.SelectedDate);

            _cuCaseTypes = ABS2.Framework.ReferenceDataWebWrapper.GetType<cuCaseType>(SessionBO.TypeAncestors, SessionBO.LCID.Value, RefDataReturnType.ListT);
            _cuStatusTypes = ABS2.Framework.ReferenceDataWebWrapper.GetType<cuStatusType>(SessionBO.TypeAncestors, SessionBO.LCID.Value, RefDataReturnType.ListT);

            if (RadComboBoxInquiryAssignedTo.SelectedIndex > 0)
            {
                RadGridActiveInquiry.DataSource = new CustomerBO().GetActiveInquiries(SessionBO.UserLocations.Keys.ToList(), dateFrom, dateTo, Convert.ToInt32(RadComboBoxInquiryAssignedTo.SelectedValue));
            }
            else
            {
                RadGridActiveInquiry.DataSource = new CustomerBO().GetActiveInquiries(SessionBO.UserLocations.Keys.ToList(), dateFrom, dateTo);
            }

}

        protected void RadGridActiveInquiry_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "ExportToExcel")
            {                
                RadGridActiveInquiry.ExportSettings.ExportOnlyData = true;
                RadGridActiveInquiry.MasterTableView.ExportToExcel();
            }
            else if (e.CommandName == "ExportToCsv")
            {             
                RadGridActiveInquiry.ExportSettings.ExportOnlyData = true;
                RadGridActiveInquiry.MasterTableView.ExportToCSV();
            }
        }

        protected void RadGridActiveInquiry_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                var item = (GridDataItem)e.Item;
                var dataItem = item.DataItem as SalesInquiry;
                if (dataItem != null)
                {
                    // Solo Menu Items
                    var linkButtonStatus = e.Item.FindControl("LinkButtonStatus") as LinkButton;
                    var linkButtonTransfer = e.Item.FindControl("LinkButtonTransfer") as LinkButton;
                    var linkButtonCopy = e.Item.FindControl("LinkButtonCopy") as LinkButton;

                    try
                    {
                        var radToolTip1 = e.Item.FindControl("RadToolTip1") as RadToolTip;

                        if (radToolTip1 != null)
                        {
                            if (linkButtonStatus != null)
                            {
                                linkButtonStatus.OnClientClick =
                                    String.Format(
                                        "CloseRadToolTip('" + radToolTip1.ClientID +
                                        "'); return ShowSoloForm('{0}','{1}');",
                                        dataItem.CustomerId, "Status");
                            }

                            if (linkButtonTransfer != null)
                            {
                                linkButtonTransfer.OnClientClick =
                                    String.Format(
                                        "CloseRadToolTip('" + radToolTip1.ClientID +
                                        "'); return ShowSoloForm('{0}','{1}');",
                                        dataItem.CustomerId, "Transfer");
                            }

                            if (linkButtonCopy != null)
                            {
                                linkButtonCopy.OnClientClick =
                                    String.Format(
                                        "CloseRadToolTip('" + radToolTip1.ClientID +
                                        "'); return ShowSoloForm('{0}','{1}');",
                                        dataItem.CustomerId, "Copy");
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        ABS2.Framework.LogExceptions.LogException(err, this.Request, SessionBO.User.usUserId,
                                                              SessionBO.User.userName);
                    }
                }
                    }
                }

        protected void RadGridActiveInquiry_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem item = (GridDataItem)e.Item;
                SalesInquiry dataItem = item.DataItem as SalesInquiry;
                if (dataItem != null)
                {
                    LinkButton linkButtonCustomer = (LinkButton)item["ClientName"].FindControl("LinkButtonDetails");
                    if (linkButtonCustomer != null)
                    {
                        linkButtonCustomer.Text = dataItem.ClientName.Length < 3 ? Resources.ApplicationConstants.ActiveInquiry_ClientName : dataItem.ClientName;
                        linkButtonCustomer.Attributes.Add("id", dataItem.CustomerId.ToString());
                    }
                    Func<cuCaseType, bool> filterCaseT = c => c.cuCaseTypeId.Equals(dataItem.InquiryCaseTypeId);
                    
                    var caseType = _cuCaseTypes.FirstOrDefault(filterCaseT);
                    if (caseType != null)
                    {
                        if (!String.IsNullOrWhiteSpace(_cuCaseTypes[0].typeName))
                            item["CaseType"].Text = caseType.typeName == null ? string.Empty : caseType.typeName;
                    }
                    Func<cuStatusType, bool> filterST = c => c.cuStatusTypeId.Equals(dataItem.StatusTypeId);


                    var statusType = _cuStatusTypes.FirstOrDefault(filterST);
                    if (statusType != null)
                    {
                        if (!String.IsNullOrWhiteSpace(_cuStatusTypes[0].typeName))
                            item["Status"].Text = statusType.typeName == null ? string.Empty : statusType.typeName;
                    }
                }
            }
        }

        protected void LinkButtonDetails_Click(object sender, EventArgs e)
        {
            List<string> selectedItems = new List<string>();
            foreach (GridDataItem gdi in RadGridActiveInquiry.SelectedItems)
            {
                selectedItems.Add(gdi.GetDataKeyValue("CustomerId").ToString());
            }
            LinkButton linkButtonDetails = (LinkButton)sender;
            selectedItems.Add(linkButtonDetails.Attributes["id"]);
            Response.Redirect("CustomerDetail.aspx?ID=" + linkButtonDetails.Attributes["id"] + "&GCIDS=" + string.Join(",", selectedItems) + "&type=1");
        }
        }
}


The animated GIF is attached for your reference.

Please suggest your thoughts.

Regards,
Srriam








4 Answers, 1 is accepted

Sort by
0
Sriram
Top achievements
Rank 1
answered on 07 Aug 2014, 04:22 PM
Can some one help me on this?
0
Princy
Top achievements
Rank 2
answered on 08 Aug 2014, 04:43 AM
Hi Sriram,

This is expected behavior as when you click on the Export button, the NeedDataSource event is fired and hence the Grid is bound with data and that is exported to Excel or CSV, hence the Grid is not empty, but this will not affect the Grid.

Thanks,
Princy
0
Sriram
Top achievements
Rank 1
answered on 08 Aug 2014, 07:01 AM
Hi Princy, 

Thanks for you reply.

This is a bug in my application. It states that, the Export to Excel / CSV should not be populated when the Grid is not displaying any value. By default, when the user lands to the page, without giving any search criteria, when clicking on the Export to Excel / CSV, the data gets populated.

To avoid this, the grid should be invisible and should be made visible only when the search is invoked. But I need to fix the bug in such a way that the grid will be displayed with empty data and when it has no data, Export should have empty rows.







0
Princy
Top achievements
Rank 2
answered on 11 Aug 2014, 04:55 AM
Hi Sriram,

As a suggestion what you can do is, check if the items in Grid is empty while exporting, and bind the Grid to empty datasource as shown below:

C#:
bool isExport = false;
protected void rgrdSample_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
    if ((rgrdSample.Items.Count <= 0) && (isExport))
    {
        rgrdSample.DataSource = String.Empty;
    }
    else
    {
        rgrdSample.DataSource = GetDataTable();
    }
}
protected void rgrdSample_ItemCommand(object sender, GridCommandEventArgs e)
{
    if (e.CommandName == RadGrid.ExportToExcelCommandName || e.CommandName == RadGrid.ExportToCsvCommandName)
    {
        isExport = true;
    }
}

Thanks,
Princy
Tags
Grid
Asked by
Sriram
Top achievements
Rank 1
Answers by
Sriram
Top achievements
Rank 1
Princy
Top achievements
Rank 2
Share this question
or