AJAX only works once w/ Radcombobox, then freezes box.

13 posts, 0 answers
  1. Todd
    Todd avatar
    24 posts
    Member since:
    Sep 2007

    Posted 08 Jul 2010 Link to this post

    I am putting together code to refresh a radcombobox (ddlNWAGroup) w/ ajax after making a selection from a previous radcombobox (ddlGroup).  The loading panel displays and the box (ddlNWAGroup) refreshes once, but I am unable to click on the refreshed box.  It seems locked or frozen.  Is this a known problem or am I missing something?

    Here is the ascx code:
     

     

     

    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
         <AjaxSettings>
             <telerik:AjaxSetting AjaxControlID="ddlGroup">
                 <UpdatedControls>
                     <telerik:AjaxUpdatedControl ControlID="ddlNWAGroup" LoadingPanelID="RadAjaxLoadingPanel1" />
                 </UpdatedControls>
             </telerik:AjaxSetting>
         </AjaxSettings>
     </telerik:RadAjaxManager>
    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
    Groups: 
     <telerik:RadComboBox ID="ddlGroup" runat="server" Skin="WebBlue" 
         BorderStyle="Ridge" BorderWidth="1px" Width="300px"
         onselectedindexchanged="ddlGroup_SelectedIndexChanged">
         <CollapseAnimation duration="200" type="OutQuint" />
     </telerik:RadComboBox>
     <br />
     NWA Groups: 
     <telerik:RadComboBox ID="ddlNWAGroup" runat="server" Skin="WebBlue" 
         BorderStyle="Ridge" BorderWidth="1px" Width="300px">
         <CollapseAnimation duration="200" type="OutQuint" />
     </telerik:RadComboBox>
     </telerik:RadCodeBlock>
     <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" Runat="server" 
         height="75px" width="75px">
         <img alt="progress bar" src="/_layouts/IMAGES/HardwareEngineeringProcess/progressbar.gif" 
             style="width: 200px; height: 20px" />
     </telerik:RadAjaxLoadingPanel>
  2. Maria Ilieva
    Admin
    Maria Ilieva avatar
    4017 posts

    Posted 12 Jul 2010 Link to this post

    Hi Todd,

    Could you please let me know if the problem appears only in IE8 browser or in all browsers? If this behavior is observed only in IE this is cause by a bug in the browser. The mentioned bug in IE is that after several AjaxRequests the input elements on the page (combo boxes, asp TextBox, RadTextBox, ect.) loses their states. The problem could be also replicated with regular asp UpdatePanel and asp TextBox. We are still working on this problem and try to find a global way for resolving it, nonetheless it is a browser issue.
    Currently the only option to overcome this behavior is to blur the problematic input and after that focus it again.

    Greetings,
    Maria Ilieva
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Rob
    Rob avatar
    43 posts
    Member since:
    Aug 2010

    Posted 30 Sep 2010 Link to this post

    I'm seeing this in IE8, Firefox 4.0 beta and Chrome.  If I click on the first combo the items appear, but after that no mouse click can make the combo reappear.  Items are still selectable by keyboard.  The combos are in a user control which is inside a RadAjaxPanelpanel - is there anything specific I should check to investigate the problem further?

    Rob

    --edit: I built a test page and couldn't replicate the issue, so something on our page is obviously interfering with the event handlers of the RadComboBox.  Is there some documentation somewhere of what these event handlers might be?
  5. Maria Ilieva
    Admin
    Maria Ilieva avatar
    4017 posts

    Posted 01 Oct 2010 Link to this post

    Hi Rob,

    As the provided information is not enough to isolate the root cause of the issue you are facing, please prepare a simple, fully runnable reproduction demo, open a new support ticket and send it to us along with very detailed reproduction steps and explanations and we will debug it locally and we will do our best to help.

    All the best,
    Maria Ilieva
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  6. Rob
    Rob avatar
    43 posts
    Member since:
    Aug 2010

    Posted 01 Oct 2010 Link to this post

    Hi Maria.  As I stated in my edit above, when I tried to recreate the problem in a simplified test page I couldn't replicate.  I'm not asking for you to debug it, I just want to know if there's any documentation for what the various DOM event handlers are for the control.

    Rob
  7. Maria Ilieva
    Admin
    Maria Ilieva avatar
    4017 posts

    Posted 06 Oct 2010 Link to this post

    Hi Rob,

    Please  refer to the following help topic which provides list for the RadAjax client events.


    Best wishes,
    Maria Ilieva
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  8. Jez Pile
    Jez Pile avatar
    3 posts
    Member since:
    Apr 2010

    Posted 03 Nov 2010 Link to this post

    Having the same issues here.
  9. Maria Ilieva
    Admin
    Maria Ilieva avatar
    4017 posts

    Posted 08 Nov 2010 Link to this post

    Hello Jez,

    Could you please elaborate a bit more on your issue? Are you facing the same problem in exactly the same scenario? Please prepare a simple, fully runnable reproduction demo, open a new support ticket and send it to us along with very detailed reproduction steps and explanations and we will debug it locally and we will do our best to help.

    Greetings,
    Maria Ilieva
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  10. J
    J avatar
    3 posts
    Member since:
    Feb 2015

    Posted 05 Feb 2015 in reply to Maria Ilieva Link to this post

    Hello,

    I'm having a similar problem with a rad combo that determines the contents of another rad combo (with check boxes = true). After selected index changed event happens on the server, the dependant combo's items are updated successfully but the checkboxes start behaving as if they are readonly. Both rad combos are in a RadAjaxManager.

    Was there a solution to Jez and Rob's issues?

    Thanks,
    Jon


    aspx radCombo Code snippet:

        <h5><br>      Select Service Provider</h5><br>    <telerik:RadComboBox ID="rcbServiceProvider" runat="server" AppendDataBoundItems="true"<br>      EnableLoadOnDemand="true" Enabled="true" DropDownAutoWidth="Disabled" AllowCustomText="false"<br>      AutoPostBack="true" CausesValidation="false" OnSelectedIndexChanged="rcbServiceProvider_SelectedIndexChanged"<br>      CssClass="rad-select-3col"><br>      <Items><br>        <telerik:RadComboBoxItem Value="-1" Text="Please select" /><br>      </Items><br>    </telerik:RadComboBox><br><br><br><br><br><br><br><br><br><br><br>

     
          <h5><br>          Regions<br>        </h5><br>        <telerik:RadComboBox ID="rcbFilterRegion" runat="server" AppendDataBoundItems="true"<br>          EnableLoadOnDemand="true" Enabled="true" DropDownAutoWidth="Disabled" AllowCustomText="false"<br>          AutoPostBack="false" CausesValidation="false" CheckBoxes="true" CssClass="rad-select-3col"><br>          <Items><br>            <telerik:RadComboBoxItem Text="All regions" Value="" /><br>          </Items><br>        </telerik:RadComboBox><br><br>


  11. Maria Ilieva
    Admin
    Maria Ilieva avatar
    4017 posts

    Posted 06 Feb 2015 Link to this post

    Hi J,

     We were not able to replicate such an issue on our and so to provide solution for it. Can I kindly ask you to post your page markup as well as the related code behind so that we can use them to recreate the issue locally and advise you further?

    Regards,
    Maria Ilieva
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
  12. J
    J avatar
    3 posts
    Member since:
    Feb 2015

    Posted 08 Feb 2015 in reply to Maria Ilieva Link to this post

    Maria Ilieva said:Hi J,

     We were not able to replicate such an issue on our and so to provide solution for it. Can I kindly ask you to post your page markup as well as the related code behind so that we can use them to recreate the issue locally and advise you further?

    Regards,
    Maria Ilieva
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     


    Hi Maria,
    Please see below... (thanks!)

    <%@ Page Title="" Language="C#" MasterPageFile="~/RMS22.master" AutoEventWireup="true"
      CodeBehind="PurchasedAndExceptionNumbers.aspx.cs" Inherits="RMS.UI.PurchasedAndExceptionNumbers" %>

    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
      <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" DefaultLoadingPanelID="RadAjaxLoadingPanel1"
        ClientEvents-OnRequestStart="ajaxRequestStarted" ClientEvents-OnResponseEnd="ajaxRespondEnded">
        <%--    <AjaxSettings>;
            <telerik:AjaxSetting AjaxControlID="rcbFilterRegion">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="rdgPurchasedNumbers" LoadingPanelID="RadAjaxLoadingPanel1" UpdatePanelRenderMode="Inline" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>--%>
        <AjaxSettings>
          <telerik:AjaxSetting AjaxControlID="div-purchased-detail">
            <UpdatedControls>
              <telerik:AjaxUpdatedControl ControlID="div-purchased-detail" LoadingPanelID="RadAjaxLoadingPanel1"
                UpdatePanelRenderMode="Inline" />
            </UpdatedControls>
          </telerik:AjaxSetting>
        </AjaxSettings>
        <AjaxSettings>
          <telerik:AjaxSetting AjaxControlID="rcbServiceProvider">
            <UpdatedControls>
              <telerik:AjaxUpdatedControl ControlID="rdgPurchasedNumbers" LoadingPanelID="RadAjaxLoadingPanel1"
                UpdatePanelRenderMode="Inline" />
              <telerik:AjaxUpdatedControl ControlID="div-purchased-detail" LoadingPanelID="RadAjaxLoadingPanel1"
                UpdatePanelRenderMode="Inline" />
              <%--<telerik:AjaxUpdatedControl ControlID="grid_filter_panel" LoadingPanelID="RadAjaxLoadingPanel1"
                UpdatePanelRenderMode="Inline" />--%>
              <telerik:AjaxUpdatedControl ControlID="rcbFilterRegion" LoadingPanelID="RadAjaxLoadingPanel1"
                UpdatePanelRenderMode="Inline" />
            </UpdatedControls>
          </telerik:AjaxSetting>
        </AjaxSettings>
        <AjaxSettings>
          <telerik:AjaxSetting AjaxControlID="rdgPurchasedNumbers">
            <UpdatedControls>
              <telerik:AjaxUpdatedControl ControlID="rdgPurchasedNumbers" LoadingPanelID="RadAjaxLoadingPanel1"
                UpdatePanelRenderMode="Inline" />
              <telerik:AjaxUpdatedControl ControlID="div-purchased-detail" LoadingPanelID="RadAjaxLoadingPanel1"
                UpdatePanelRenderMode="Inline" />
              <%--<telerik:AjaxUpdatedControl ControlID="rcbFilterRegion" LoadingPanelID="RadAjaxLoadingPanel1" UpdatePanelRenderMode="Inline" />          --%>
            </UpdatedControls>
          </telerik:AjaxSetting>
        </AjaxSettings>
        <AjaxSettings>
          <telerik:AjaxSetting AjaxControlID="rwnEditPurchased">
            <UpdatedControls>
              <telerik:AjaxUpdatedControl ControlID="rwnEditPurchased" LoadingPanelID=""
                UpdatePanelRenderMode="Inline" />
            </UpdatedControls>
          </telerik:AjaxSetting>
        </AjaxSettings>
        <AjaxSettings>
          <telerik:AjaxSetting AjaxControlID="btnRefresh">
            <UpdatedControls>
              <telerik:AjaxUpdatedControl ControlID="rdgPurchasedNumbers" LoadingPanelID="RadAjaxLoadingPanel1"
                UpdatePanelRenderMode="Inline" />
            </UpdatedControls>
          </telerik:AjaxSetting>
        </AjaxSettings>
      </telerik:RadAjaxManager>
      <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Transparency="50"
        IsSticky="true" BackColor="#AAAAAA" MinDisplayTime="6000">
        <%--<asp:Image ID="Image1" runat="server" ImageUrl="~/images/5-1.gif"></asp:Image>--%>
      </telerik:RadAjaxLoadingPanel>
      <%--                          --%>
      <div class="div-purchased-detail">
        <asp:Label ID="lblUpdateResult" runat="server" CssClass="update-result" ClientIDMode="Static"></asp:Label>
        <h3>
          Purchased and exception numbers</h3>
        <h5>
          Select Service Provider</h5>
        <telerik:RadComboBox ID="rcbServiceProvider" runat="server" AppendDataBoundItems="true"
          EnableLoadOnDemand="true" Enabled="true" DropDownAutoWidth="Disabled" AllowCustomText="false"
          AutoPostBack="true" CausesValidation="false" OnSelectedIndexChanged="rcbServiceProvider_SelectedIndexChanged"
          CssClass="rad-select-3col">
          <Items>
            <telerik:RadComboBoxItem Value="-1" Text="Please select" />
          </Items>
        </telerik:RadComboBox>
        <p />

        <div id="grid_filter_panel" runat="server" visible="true" style="background-color: #ecf6f7; height: 100%;">
          <h3 id="grid_filter_panel_heading" style="background-color: #ecf6f7; cursor: pointer;" onclick="toggleGridFilterPanel();">
            Grid filter
          </h3>
          <div id="grid_filter_panel_elements">

            <h5>
              Regions
            </h5>
            <telerik:RadComboBox ID="rcbFilterRegion" runat="server" AppendDataBoundItems="true"
              EnableLoadOnDemand="true" Enabled="true" DropDownAutoWidth="Disabled" AllowCustomText="false"
              AutoPostBack="false" CausesValidation="false" CheckBoxes="true" CssClass="rad-select-3col">
              <Items>
                <telerik:RadComboBoxItem Text="All regions" Value="" />
              </Items>
            </telerik:RadComboBox>
            <h3 class="nextLine"></h3>
            <h5>
              Service Types
            </h5>
            <telerik:RadComboBox ID="rcbFilterServiceType" runat="server" AppendDataBoundItems="true"
              EnableLoadOnDemand="true" Enabled="true" DropDownAutoWidth="Disabled" AllowCustomText="false"
              AutoPostBack="false" CausesValidation="false" CheckBoxes="true" CssClass="rad-select-3col">
              <Items>
                <telerik:RadComboBoxItem Text="All service types" Value="" />
              </Items>
            </telerik:RadComboBox>

            <h3 class="nextLine"></h3>
            <h5>
              Purchased Number
            </h5>
            <telerik:RadNumericTextBox  Label="From" id="tbxPurchasedNumFrom" runat="server" ClientIdMode="static" width="82px" max="9999" min="0" DataType="System.Int32" MaxLength="4" NumberFormat-DecimalDigits="0" NumberFormat-GroupSeparator=""></telerik:RadNumericTextBox>
            <telerik:RadNumericTextBox Label="To" id="tbxPurchasedNumTo" runat="server" ClientIdMode="static" width="82px" max="9999" min="0" DataType="System.Int32" MaxLength="4" NumberFormat-DecimalDigits="0" NumberFormat-GroupSeparator=""></telerik:RadNumericTextBox>
      <%--      <table>
              <tr>
                <td>
                  <h5>
                    Select Regions
                  </h5>
                </td>
                <td>
                  <telerik:RadComboBox ID="rcbFilterRegion" runat="server" AppendDataBoundItems="true"
                    EnableLoadOnDemand="true" Enabled="true" DropDownAutoWidth="Disabled" AllowCustomText="false"
                    AutoPostBack="false" CausesValidation="false" CheckBoxes="true" CssClass="rad-select-3col">
                    <Items>
                      <telerik:RadComboBoxItem Text="All regions" Value="" />
                    </Items>
                  </telerik:RadComboBox>
                </td>
              </tr>
              <tr>
                <td>
                  <h5>
                    Select Service Types
                  </h5>
                </td>
                <td>
                  <telerik:RadComboBox ID="rcbFilterServiceType" runat="server" AppendDataBoundItems="true"
                    EnableLoadOnDemand="true" Enabled="true" DropDownAutoWidth="Disabled" AllowCustomText="false"
                    AutoPostBack="false" CausesValidation="false" CheckBoxes="true" CssClass="rad-select-3col">
                    <Items>
                      <telerik:RadComboBoxItem Text="All service types" Value="" />
                    </Items>
                  </telerik:RadComboBox>
                </td>
              </tr>
            </table>--%>
            <div class="">
            </div>
            <%--style="border: 1px solid black; height: 21px;"--%>
            <div class="">
            </div>
            <%--style="border: 1px solid black;"--%>
            <div class="div-command-button">
              <asp:Button ID="btnRefresh" runat="server" Text="Refresh" OnClick="btnRefresh_Click" />
            </div>
          </div>
        </div>
      </div>
      <asp:Panel ID="pnlPurchaseQuery" runat="server" ClientIDMode="Static">
        <div style="border: 1px solid #C9C9C9 !important; margin-top: -7px; width: 800px;">
          <telerik:RadGrid ID="rdgPurchasedNumbers" runat="server" AllowFilteringByColumn="false"
            FilterType="CheckList" AllowPaging="true" PageSize="14" AllowSorting="true" AutoGenerateColumns="false"
            EnableEmbeddedSkins="True" EnableLinqExpressions="false" GridLines="None" FilterMenu-CausesValidation="false"
            ShowFooter="True" ShowGroupPanel="false" HeaderStyle-BackColor="ActiveCaption"
            OnNeedDataSource="rdgPurchasedNumbers_NeedDataSource" OnDetailTableDataBind="rdgPurchasedNumbers_DetailTableDataBind"
            OnInit="RadGrid_init" BorderStyle="None" OnItemCreated="RadGrid_ItemCreated" OnItemEvent="RadGrid_ItemEvent"
            OnSortCommand="RadGrid_sortCommand" OnItemDataBound="rdgPurchasedNumbers_ItemDataBound"
            OnPreRender="rdgPurchasedNumbers_preRender" GroupingSettings-CaseSensitive="false">
            <MasterTableView CommandItemDisplay="None" DataKeyNames="PurchasedFacilityGroupId"
              ShowGroupFooter="False" GroupLoadMode="Client" TableLayout="Fixed" Width="802px"
              AllowMultiColumnSorting="true" Name="LatestPurchased">
              <DetailTables>
                <telerik:GridTableView DataKeyNames="PurchasedFacilityGroupId" Name="PurchasedHistory"
                  Width="660px" AllowFilteringByColumn="false" BorderStyle="Solid" BorderWidth="3px"
                  ShowFooter="false" AllowSorting="false" AllowPaging="true" PageSize="10">
                  <HeaderStyle BackColor="Gray" ForeColor="White" />
                  <Columns>
                    <telerik:GridBoundColumn DataField="PurchasingId" Visible="false" DataType="System.Int32">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="PurchasedFacilityGroupId" Visible="false" DataType="System.Int32">
                    </telerik:GridBoundColumn>
                    <telerik:GridTemplateColumn UniqueName="TotalPurchased" AllowFiltering="false" HeaderText="Total purchased"
                      AutoPostBackOnFilter="false" DataType="System.String" DataField="TotalPurchased">
                      <ItemTemplate>
                        <asp:Label ID="lblTotalPurchase" runat="server" Text='<%#Bind("TotalPurchased")%>'
                          ToolTip='<%#BuildComment((object)Eval("Comment")) %>' />
                      </ItemTemplate>
                    </telerik:GridTemplateColumn>
                    <telerik:GridTemplateColumn UniqueName="Comment" AllowFiltering="false" HeaderText="Comment"
                      AutoPostBackOnFilter="false" DataType="System.String" DataField="Comment">
                      <ItemTemplate>
                        <%--Width="80px" Height="30px" BackColor="Aquamarine" BorderStyle="Solid" --%>
                        <asp:Label ID="lblComment" runat="server" Text='<%#BuildCommentPreview((object)Eval("Comment")) %>'
                          ToolTip='<%#BuildComment((object)Eval("Comment")) %>' />
                      </ItemTemplate>
                    </telerik:GridTemplateColumn>
                    <%--<telerik:GridBoundColumn SortExpression="CostPerDay" HeaderText="Cost per day" HeaderButtonType="TextButton" DataField="CostPerDay" DataFormatString="{0:C}" DataType="System.Decimal"></telerik:GridBoundColumn>--%>
                    <telerik:GridTemplateColumn UniqueName="PurchasedCreatedDate" AllowFiltering="false"
                      HeaderText="Created in system date" AutoPostBackOnFilter="false" DataType="System.DateTime"
                      DataField="PurchasedCreatedDate">
                      <ItemTemplate>
                        <asp:Label ID="lblHistoryDatePurchasedCreatedDate" runat="server" Text='<%#DisplayShortDate((object)Eval("PurchasedCreatedDate"))%>' />
                      </ItemTemplate>
                    </telerik:GridTemplateColumn>
                    <telerik:GridTemplateColumn UniqueName="PurchasedEndedByUserName" AllowFiltering="false"
                      HeaderText="Updated by" AutoPostBackOnFilter="false" DataType="System.String" DataField="PurchasedEndedByUserName">
                      <ItemTemplate>
                        <asp:Label ID="lblPurchasedEndedByUserName" runat="server" Text='<%#Bind("PurchasedEndedByUserName")%>' />
                      </ItemTemplate>
                    </telerik:GridTemplateColumn>
                  </Columns>
                </telerik:GridTableView>
              </DetailTables>
              <PagerStyle AlwaysVisible="true" Mode="NextPrevAndNumeric" />
              <CommandItemSettings ShowRefreshButton="false" ShowAddNewRecordButton="false" />
              <HeaderStyle ForeColor="#41519A" BackColor="#ADD9DD" Font-Bold="true" Font-Size="9pt" />
              <FilterItemStyle Font-Size="8pt" />
              <Columns>
                <telerik:GridTemplateColumn UniqueName="GroupId" AllowFiltering="false" AutoPostBackOnFilter="false"
                  DataType="System.Int32" DataField="PurchasedFacilityGroupId">
                  <HeaderStyle Width="0"></HeaderStyle>
                  <ItemTemplate>
                    <asp:HiddenField ID="hdnPurchasedGroupId" runat="server" Value='<%#Bind("PurchasedFacilityGroupId") %>' />
                  </ItemTemplate>
                </telerik:GridTemplateColumn>
                <telerik:GridTemplateColumn UniqueName="Region" HeaderText="Region" FilterControlWidth="0px"
                  AllowFiltering="true" AutoPostBackOnFilter="true" SortExpression="Region" FilterListOptions="VaryByDataType"
                  AndCurrentFilterFunction="EqualTo" DataType="System.String" DataField="Region">
                  <HeaderStyle Width="115px"></HeaderStyle>
                  <%--<FilterTemplate>
                    <telerik:RadComboBox ID="rcbFilterRegion" Visible="true" AllowCustomText="false" DataTextField="Region"
                      DataValueField="Region" DropDownAutoWidth="Disabled" DropDownWidth="250px" Width="99%"
                      OnClientSelectedIndexChanged="filterChanged" Height="120px" AppendDataBoundItems="true"
                      EnableViewState="true" runat="server" AutoPostBack="false" CheckBoxes="true">
                      <Items>
                        <telerik:RadComboBoxItem Text="All regions" Value="" />
                      </Items>
                    </telerik:RadComboBox>
                  </FilterTemplate>--%>
                  <ItemTemplate>
                    <asp:Label ID="fldRegion" runat="server" Text='<%#Bind("Region") %>' />
                    <asp:HiddenField ID="hdnServiceProviderId" runat="server" Value='<%#Bind("ServiceProviderId") %>' />
                    <asp:HiddenField ID="hdnRegionId" runat="server" Value='<%#Bind("RegionId")%>' />
                  </ItemTemplate>
                </telerik:GridTemplateColumn>
                <telerik:GridTemplateColumn UniqueName="ServiceType" HeaderText="Service Type" FilterControlWidth="135px"
                  AllowFiltering="true" AutoPostBackOnFilter="true" CurrentFilterFunction="EqualTo"
                  SortExpression="ServiceType" DataType="System.String" FilterListOptions="VaryByDataType"
                  DataField="ServiceType">
                  <HeaderStyle Width="150px"></HeaderStyle>
                  <%--              <FilterTemplate>
                    <telerik:RadComboBox ID="rcbFilterServiceType" AllowCustomText="false" DataTextField="ServiceTypeName"
                      DataValueField="ServiceTypeName" DropDownAutoWidth="Disabled" DropDownWidth="250px"
                      Width="99%" OnClientSelectedIndexChanged="filterChanged" Height="120px" AppendDataBoundItems="true"
                      EnableViewState="true" runat="server" AutoPostBack="false">
                      <Items>
                        <telerik:RadComboBoxItem Text="All service types" Value="" />
                      </Items>
                    </telerik:RadComboBox>
                  </FilterTemplate>--%>
                  <ItemTemplate>
                    <asp:Label ID="fldServiceType" runat="server" Text='<%#Bind("ServiceType") %>' />
                    <asp:HiddenField ID="hdnServiceTypeId" runat="server" Value='<%#Bind("ServiceTypeId") %>' />
                  </ItemTemplate>
                </telerik:GridTemplateColumn>
                <telerik:GridTemplateColumn UniqueName="FundingTypeName" HeaderText="Funding Type"
                  FilterControlWidth="90px" AllowFiltering="false" AutoPostBackOnFilter="true" CurrentFilterFunction="EqualTo"
                  SortExpression="ViabilityText" DataType="System.String" FilterListOptions="VaryByDataType"
                  DataField="FundingTypeName">
                  <HeaderStyle Width="105px"></HeaderStyle>
                  <%--              <FilterTemplate>
                    <telerik:RadComboBox ID="rcbFilterFundingType" AllowCustomText="false" DataTextField="FundingTypeName"
                      DataValueField="FundingTypeName" DropDownAutoWidth="Disabled" DropDownWidth="250px"
                      Width="99%" OnClientSelectedIndexChanged="filterChanged" Height="120px" AppendDataBoundItems="true"
                      EnableViewState="true" runat="server" AutoPostBack="false">
                      <Items>
                        <telerik:RadComboBoxItem Text="All funding types" Value="" />
                      </Items>
                    </telerik:RadComboBox>
                  </FilterTemplate>--%>
                  <ItemTemplate>
                    <asp:Label ID="fldFundingTypeName" runat="server" Text='<%#Bind("FundingTypeName") %>' />
                    <asp:HiddenField ID="hdnFundingTypeId" runat="server" Value='<%#Bind("FundingTypeId") %>' />
                  </ItemTemplate>
                </telerik:GridTemplateColumn>
                <telerik:GridTemplateColumn UniqueName="TotalPurchased" AllowFiltering="false" HeaderText="Purchased Number"
                  FilterControlWidth="42px" AutoPostBackOnFilter="true" CurrentFilterFunction="EqualTo"
                  SortExpression="TotalPurchased" DataType="System.Int32" FilterListOptions="VaryByDataType"
                  DataField="Number">
                  <HeaderStyle Width="60px"></HeaderStyle>
                  <ItemTemplate>
                    <asp:Label ID="lblTotalPurchased" runat="server" Text='<%#Bind("TotalPurchased") %>'
                      ToolTip='<%#BuildComment((object)Eval("Comment")) %>' />
                  </ItemTemplate>
                </telerik:GridTemplateColumn>
                <telerik:GridTemplateColumn UniqueName="BeingOccupied" AllowFiltering="false" HeaderText="Used Numbers"
                  FilterControlWidth="42px" AutoPostBackOnFilter="true" CurrentFilterFunction="EqualTo"
                  SortExpression="BeingOccupied" DataType="System.Int32" FilterListOptions="VaryByDataType"
                  DataField="Number">
                  <HeaderStyle Width="60px"></HeaderStyle>
                  <ItemTemplate>
                    <asp:Label ID="lblTotalOccupied" runat="server" Text='<%#Bind("BeingOccupied") %>' />
                  </ItemTemplate>
                </telerik:GridTemplateColumn>
                <%--            <telerik:GridTemplateColumn UniqueName="CostPerDay" 
                                            AllowFiltering="false"
                                            HeaderText="Cost Per Day"
                                            FilterControlWidth="42px" 
                                            AutoPostBackOnFilter="true" 
                                            CurrentFilterFunction="Contains"
                                            SortExpression="CostPerDay" 
                                            DataType="System.Decimal" 
                                            FilterListOptions="VaryByDataType"
                                            DataField="CostPerDay">
                  <HeaderStyle Width="60px"></HeaderStyle>
                  <ItemTemplate>
                    <asp:Label ID="lblCostPerDay" runat="server" Text='<%#CostPerDayFormatter((object)Eval("CostPerDay")) %>' />
                  </ItemTemplate>
                </telerik:GridTemplateColumn>            
                --%>
                <telerik:GridTemplateColumn UniqueName="Action" HeaderText="Action" AllowFiltering="false"
                  ItemStyle-CssClass="center-cell">
                  <HeaderStyle Width="70px" HorizontalAlign="Center" VerticalAlign="Top"></HeaderStyle>
                  <ItemTemplate>
                    <asp:LinkButton ID="lkbEdit" runat="server" Text="Edit" CssClass="linkbutton_link"
                      Enabled="true" />
                  </ItemTemplate>
                </telerik:GridTemplateColumn>
              </Columns>
            </MasterTableView>
            <ClientSettings Selecting-AllowRowSelect="True" AllowKeyboardNavigation="False" EnablePostBackOnRowClick="False"
              EnableRowHoverStyle="False" ReorderColumnsOnClient="False" AllowDragToGroup="False"
              AllowColumnsReorder="False">
              <Selecting AllowRowSelect="False"></Selecting>
              <Scrolling AllowScroll="False" UseStaticHeaders="true" />
              <Resizing AllowColumnResize="false" EnableRealTimeResize="false" AllowResizeToFit="false" />
            </ClientSettings>
            <FilterMenu EnableImageSprites="False">
            </FilterMenu>
          </telerik:RadGrid>
        </div>
      </asp:Panel>
      <asp:HiddenField ID="hdnIsQuerying" runat="server" ClientIDMode="Static" />
      <telerik:RadWindow ID="rwnEditPurchased" runat="server" AutoSize="false" Behaviors="None"
        CenterIfModal="true" DestroyOnClose="true" EnableAjaxSkinRendering="true" Height="450"
        Modal="true" ShowContentDuringLoad="false" VisibleStatusbar="false" Width="470">
        <ContentTemplate>
          <div id="Div1" style="width: 450px;">
            <fieldset class="no-border">
              <div id="lblUpdateInfo" class="purchase-edit-form-info">
              </div>
              <asp:HiddenField ID="hdnGroupId" runat="server" ClientIDMode="Static" />
              <asp:HiddenField ID="hdnServiceProviderId" runat="server" ClientIDMode="Static" />
              <asp:HiddenField ID="hdnRegionId" runat="server" ClientIDMode="Static" />
              <asp:HiddenField ID="hdnServiceTypeId" runat="server" ClientIDMode="Static" />
              <asp:HiddenField ID="hdnFundingType" runat="server" ClientIDMode="Static" />
              <%--<asp:HiddenField ID="hdnCost" runat="server" ClientIDMode="Static" />--%>
              <asp:HiddenField ID="hdnNumber" runat="server" ClientIDMode="Static" />
              <asp:HiddenField ID="hdnMinValue" runat="server" ClientIDMode="Static" />
              <asp:HiddenField ID="hdnUsed" runat="server" ClientIDMode="Static" />
              <asp:HiddenField ID="hdnUserId" runat="server" ClientIDMode="Static" />
              <%--style="background-color: black;" CssClass="font-error" --%>
              <div class="purchase-edit-form" style="margin-top: 25px !important;">
                <asp:Label ID="lblError" runat="server" ClientIDMode="Static" CssClass="error-summary"
                  Style="width: 300px; margin: auto; clear: both; border: 1px solid #FF0000; padding: 8px;
                  font-size: smaller; margin-bottom: 15px; color: #750B33; font-size: smaller; display: block;">
                </asp:Label>
                <div class="purchase-edit-form-line">
                  <h5 id="purchase_number_h5">
                    Purchased Number</h5>
                  <telerik:RadNumericTextBox ID="tbxPurchasedNumber" runat="server" AllowOutOfRangeAutoCorrect="false"
                    DataType="System.Int32" MaxValue="100000" MinValue="0" NumberFormat-DecimalDigits="0">
                  </telerik:RadNumericTextBox>
                </div>
                <%--            <div class="purchase-edit-form-line" id="div-cost-per-day">
                  <h5 id="sil_cost_per_day_h5">Cost per Day</h5>
                  <telerik:RadNumericTextBox ID="tbxSilCostPerDay" runat="server" AllowOutOfRangeAutoCorrect="false" DataType="Currency" MaxValue="10000" MinValue="0" NumberFormat-DecimalDigits="2"></telerik:RadNumericTextBox>
                </div>--%>
                <%--            <div class="purchase-edit-form-line">
                  <h5>
                    Purchased Date</h5>
                  <telerik:RadDatePicker ID="rdpPurchasedDate" runat="server" Calendar-CalendarCaption="Purchased Date"
                    Calendar-CultureInfo="en-AU" Calendar-EnableAjaxSkinRendering="true" Culture="en-AU"
                    EnableViewState="true" Calendar-WeekendDayStyle-Font-Italic="true" Calendar-WeekendDayStyle-Font-Bold="false"
                    DateInput-ReadOnly="true" Calendar-SelectedDayStyle-ForeColor="Blue" DateInput-DateFormat="dd-MMM-yyyy">
                  </telerik:RadDatePicker>
                </div>--%>
                <div class="purchase-edit-form-line">
                  <h5 id="purchased_comment_h5">
                    Comment</h5>
                  <telerik:RadTextBox ID="tbxPurchaseComment" runat="server" TextMode="MultiLine" Rows="4"
                    MaxLength="250">
                  </telerik:RadTextBox>
                </div>
                <div class="purchase-edit-form-line">
                  <h5>
                    &nbsp;</h5>
                  <asp:Button ID="btnEditPurchaseSubmit" runat="server" Text="Save" OnClientClick="return savePurchase();" />
                  <asp:Button ID="btnEditPurchaseCancel" runat="server" Text="Cancel" OnClientClick="return cancelEdit();" />
                </div>
              </div>
            </fieldset>
          </div>
        </ContentTemplate>
      </telerik:RadWindow>
      <input type="hidden" id="hdnIsPrimaryCarer" />
      <telerik:RadCodeBlock ID="rcBlock" runat="server">
        <script type="text/javascript">

          $(document).ready(function () {
            $(".update-result").hide();
            $("a").removeClass("aspNetDisabled");
          });

          //debugger;




          function rcbServiceType_selectedChanged(obj, e) {
            //          var x = e.get_item().get_value();
            //          var y = $find(" < % =tbxSilCostPerDay.ClientID %>");
            //          if (x == 9) {
            //            y.clear();
            //            y.set_emptyMessage("Not applicable for this Service Type");
            //            y.disable();
            //          } else {
            //            y.set_value($("#hdnOriginalCost").val());
            //            y.set_emptyMessage("");
            //            y.enable();
            //          }
            return false;
          }

          var errMsg = "";
          function validateEditForm() {

            var erLbl = $("#lblError");
            clearError(erLbl);

            var nPurchased = $find("<%=tbxPurchasedNumber.ClientID%>");

            var purchasedLbl = $("#purchase_number_h5");
            var oUsed = $("#hdnUsed").val();

            var isValid = true;

            $(purchasedLbl).removeClass("font-error");

            if (nPurchased.get_value() == "") {
              buildErrMsg("Purchased Number is mandatory.");
              isValid = false;
              $(purchasedLbl).addClass("font-error");
              $("#<%=tbxPurchasedNumber.ClientID%>").addClass("error");
            } else if (nPurchased.get_value() < oUsed) {


              isValid = false;
              buildErrMsg("Purchased Number cannot be less than Used Number.");
              purchasedLbl.addClass("font-error");
              $("#<%=tbxPurchasedNumber.ClientID%>").addClass("error");
              //$("#tbxStreetAddress").addClass("error");
              //nPurchased.addClass("error");
            }

            if (isValid == false) {
              displayError(erLbl);
            }

            return isValid;
          }

          function checkServerValidation(msg) {


            var erLbl = $("#lblError");
            clearError(erLbl);

            var purchaseNumberCtl = $find("<%=tbxPurchasedNumber.ClientID %>");
            //var e = $find(" < % =tbxSilCostPerDay.ClientID %>");
            var purchaseNumberLbl = $("#purchase_number_h5");
            //var ee = $("#sil_cost_per_day_h5");

            var isValid = true;
            //$(ae).removeClass("font-error");
            //$(be).removeClass("font-error");
            //$(ce).removeClass("font-error");
            $(purchaseNumberLbl).removeClass("font-error");
            //$(ee).removeClass("font-error");

            if (msg.toLowerCase().indexOf("validation failure") > -1) {
              isValid = false;
              var msgToDisplay = msg.replace("Validation failure: ", "");
              buildErrMsg(msgToDisplay);
            }


            //          if (a.get_value() == "-1") {
            //            buildErrMsg("CFDU Region is mandatory.");
            //            valid = false;
            //            $(ae).addClass("font-error");
            //          }

            //          if (b.get_value() == "-1") {
            //            buildErrMsg("Service Provider is mandatory.");
            //            valid = false;
            //            $(be).addClass("font-error");
            //          }

            //          if (c.get_value() == "-1") {
            //            buildErrMsg("Funding Type is mandatory.");
            //            valid = false;
            //            $(ce).addClass("font-error");
            //          }

            //          if (d.get_value() == "") {
            //            buildErrMsg("Purchased Number is mandatory.");
            //            valid = false;
            //            $(de).addClass("font-error");
            //          }
            if (!isValid) {
              displayError(erLbl);
            }

            return isValid;
          }

          function savePurchase() {

            rwnEditPurchased_lockButtons();

            var groupId = $("#hdnGroupId").val();
            var serviceProviderId = $("#hdnServiceProviderId").val();
            var regionId = $("#hdnRegionId").val();
            var serviceTypeid = $("#hdnServiceTypeId").val();
            var fundingTypeId = $("#hdnFundingType").val();
            //var oCost = $("#hdnCost").val();
            var oPurchasedNumber = $("#hdnNumber").val();
            var oMinValue = $("#hdnMinValue").val();
            var oUsed = $("#hdnUsed").val();
            //          var nCost = $find("< % = tbxSilCostPerDay.ClientID%>").get_value();
            var nPurchased = $find("<%=tbxPurchasedNumber.ClientID%>").get_value();
            //var nPurchasedDate = $find("< % = rdpPurchasedDate.ClientID%>").get_selectedDate();
            var uid = $("#hdnUserId").val();
            var nComment = $find("<%=tbxPurchaseComment.ClientID%>").get_value();

            //de.removeClass("font-error");

            var isValid = true;

            isValid = validateEditForm();

            if (!isValid) {
              displayError("#lblError");
              rwnEditPurchased_unlockButtons();
            } else {
              $("#hdnMinValue").val(nPurchased);
              //processNewPurchased(groupId, nPurchased, nPurchasedDate, nCost, nComment);
              //processNewPurchased(groupId, nPurchased, nPurchasedDate, nComment);
              processNewPurchased(groupId, nPurchased, nComment);
            }

            return false;
          }

          //        function processNewPurchased(groupId, newPurchased, newDate, newCost, nComment) {
          //function processNewPurchased(groupId, newPurchased, newDate, nComment) {
          function processNewPurchased(groupId, newPurchased, nComment) {
            var dt = new Date().getDate().toString() + "-" + (new Date().getMonth() + 1).toString() + "-" + new Date().getFullYear().toString();

            //debugger;
            //int groupId, int newPurchasedNumber, DateTime newDate, double? newCost = null
            var dat = "";
            //dat = "'groupId': '" + groupId + "', 'newPurchasedNumber': '" + newPurchased + "', 'newDate': '" + dt + "', 'uid': '" + $("#hdnUserId").val() + "', 'newCost': '" + newCost + "', 'comment': '" + nComment + "'";
            dat = "'groupId': '" + groupId + "', 'newPurchasedNumber': '" + newPurchased + "', 'newDate': '" + dt + "', 'uid': '" + $("#hdnUserId").val() + "', 'comment': '" + nComment + "'";

            $.ajax({
              url: 'PurchasedAndExceptionNumbers.aspx/SaveNewPurchase',
              type: "POST",
              dataType: "json",
              data: "{" + dat + "}",
              contentType: "application/json; charset=utf-8",
              timeout: function (t) {
                //alert("Time out!\n\n" + t);
              },
              error: function (e) {
                //alert("Error!\n\n" + e);
              },
              success: function (data) {

                //check server validation passed
                if (checkServerValidation(data.d)) {
                  refreshData(data.d);
                }
              }
            });

            return false;
          }

          function refreshData(data) {


            //          var d = data.split(",");
            //          var gid = d[0].split('_')[1];
            //          var purchased = d[1].split('_')[1];
            //          var used = d[2].split('_')[1];
            //          var cost = d[3].split('_')[1];

            //          var items = $find("< %=rdgPurchasedNumbers.ClientID%>").get_masterTableView().get_dataItems();
            //          var mview = $find("< %=rdgPurchasedNumbers.ClientID%>").get_masterTableView();
            //          var item1 = items[0];
            //          var item7 = items[6];

            //          for (var i = 0; i < items.length - 1; i++) {
            //            var g = mview.getCellByColumnUniqueName(items[i], "GroupId").innerHTML;

            //            if (g.search(gid) > -1 || g.search('value=' + gid) > -1 || g.search('value="' + gid + '"') > -1) {
            //              mview.getCellByColumnUniqueName(items[i], "TotalPurchased").innerHTML = purchased;
            //              mview.getCellByColumnUniqueName(items[i], "BeingOccupied").innerHTML = used;
            //              if ($.trim(cost).length > 0) {
            //                mview.getCellByColumnUniqueName(items[i], "CostPerDay").innerHTML = "$" + cost;
            //              }
            //            }
            //          }

            //          cancelEdit();

            //          sRegion = "";
            //          sServiceType = "";
            //          sFundingType = "";


            var masterTable = $find("<%= rdgPurchasedNumbers.ClientID %>").get_masterTableView();
            masterTable.rebind();

            return false;
          }

          var sRegion = "";
          var sServiceType = "";
          var sFundingType = "";

          // param = groupId, serviceProviderId, regionId, serviceTypeId, fundingTypeId, currentPurchased, currentUsed, costPerDay, minValue, providerName, serviceType, fundingType
          // (costPerDay removed...)   
          // param = groupId, serviceProviderId, regionId, serviceTypeId, fundingTypeId, currentPurchased, currentUsed, minValue, providerName, serviceType, fundingType
          function EditPurchaseRecord(param) {
            var erLbl = $("#lblError");
            clearError(erLbl);

            //          $find("< % = tbxSilCostPerDay.ClientID%>").clear();
            $find("<%=tbxPurchasedNumber.ClientID%>").clear();
            //$find("< % = rdpPurchasedDate.ClientID%>").set_selectedDate(new Date());
            $find("<%=tbxPurchaseComment.ClientID%>").clear();

            sRegion = "";
            sServiceType = "";
            sFundingType = "";

            var prms = param.split(",");

            var gpi = prms[0];
            var spi = prms[1];
            var rgi = prms[2];
            var sti = prms[3];
            var fti = prms[4];
            var cpi = prms[5] == "-1" ? "N/A" : prms[5];
            var cui = prms[6];
            //cost per day - removed
            //var cti = prms[7] == "-1" ? "N/A" : prms[7];
            //          var mnv = prms[8];
            //          var pvn = prms[9];
            //          var rgn = prms[10];
            //          var stn = prms[11];
            //          var ftn = prms[12];
            var mnv = prms[7];
            var pvn = prms[8];
            var rgn = prms[9];
            var stn = prms[10];
            var ftn = prms[11];

            sRegion = rgn;
            sServiceType = stn;
            sFundingType = ftn;

            var info = "<li><label>Service Provider</label><span>" + pvn + "</span></li>";
            info += "<li><label>Region</label><span>" + rgn + "</span></li>";
            info += "<li><label>Service Type</label><span>" + stn + "</span></li>";
            info += "<li><label>Funding Type</label><span>" + ftn + "</span></li>";
            info += "<li><label>Current Purchased Number</label><span>" + cpi + "</span></li>";
            info += "<li><label>Used Number</label><span>" + cui + "</span></li>";
            //          if (cti == "N/A") {
            //            info += "<li><label>Current Cost/Day</label><span>" + cti + "</span></li>";
            //          } else {
            //            info += "<li><label>Current Cost/Day</label><span>$" + cti + "</span></li>";
            //          }

            $("#hdnGroupId").val(gpi);
            $("#hdnServiceProviderId").val(spi);
            $("#hdnRegionId").val(rgi);
            $("#hdnServiceTypeId").val(sti);
            $("#hdnFundingType").val(fti);
            //$("#hdnCost").val(cti);
            $("#hdnNumber").val(cpi);
            $("#hdnMinValue").val(mnv);
            $("#hdnUsed").val(cui);

            $("#lblUpdateInfo").html(info);

            //          if (sti == 16 || sti == 17) {
            //            $("#div-cost-per-day").show();
            //          } else {
            //            $("#div-cost-per-day").hide();
            //          }

            var wnd = $find("<%=rwnEditPurchased.ClientID %>");
            wnd.set_title("New purchased number record");
            wnd.show();

            var d = $find("<%=tbxPurchasedNumber.ClientID %>");
            d.set_minValue(mnv);
            //d.set_emptyMessage("minimum " + mnv);
            d.set_emptyMessage("new total purchased number");

            return false;
          }

          function ViewHistory(param) {
            return false;
          }

          function cancelEdit() {
            $("#hdnGroupId").val("");
            $("#hdnServiceProviderId").val("");
            $("#hdnRegionId").val("");
            $("#hdnServiceTypeId").val("");
            $("#hdnFundingType").val("");
            //$("#hdnCost").val("");
            $("#hdnNumber").val("");
            $("#hdnMinValue").val("");
            $("#hdnUsed").val("");

            //          $find("< % =tbxSilCostPerDay.ClientID%>").clear();
            $find("<%=tbxPurchasedNumber.ClientID%>").clear();
            //$find("< % = rdpPurchasedDate.ClientID%>").set_selectedDate(new Date());

            var purchasedLbl = $("#purchase_number_h5");
            purchasedLbl.removeClass("font-error");

            var wnd = $find("<%=rwnEditPurchased.ClientID %>");
            wnd.close();

            var erLbl = $("#lblError");
            clearError(erLbl);

            sRegion = "";
            sServiceType = "";
            sFundingType = "";

            return false;
          }

          function buildErrMsg(msg) {
            if (errMsg == "") {
              errMsg = "<b>Please correct the following items and re-submit the form.</b><br />";
            }
            errMsg += "<li>" + msg + "</li>";
          }

          function displayError(ctrl) {
            $(ctrl).html(errMsg);
            $(ctrl).show();
          }

          function clearError(ctrl) {
            errMsg = "";
            ctrl.hide();
          }

          function RegionFilterChanged(sender, args) {
          }

          function ajaxRespondEnded(sender, args) {
            $find("<%=rcbServiceProvider.ClientID%>").enable();
            $("input").click(function (e) { return true; });
          }

          function ajaxRequestStarted(sender, args) {
            $find("<%=rcbServiceProvider.ClientID%>").disable();
            $("input").click(function (e) { e.preventDefault(); });
          }

          function filterChanged(sender, args) {
            var tv = $find("<%=rdgPurchasedNumbers.ClientID %>").get_masterTableView();
            var ctl = "";
            if (sender.get_id().indexOf('rcbFilterRegion') >= 0) {
              ctl = "Region";
            } else if (sender.get_id().indexOf('rcbFilterServiceType') >= 0) {
              ctl = "ServiceType";
            } else if (sender.get_id().indexOf('rcbFilterFundingType') >= 0) {
              ctl = "FundingTypeName";
            } else {

            }

            if ($.trim(args.get_item().get_value()) != "") {
              tv.filter(ctl, args.get_item().get_text(), "EqualTo");
            } else {
              tv.filter(ctl, "", Telerik.Web.UI.GridFilterFunction.NoFilter);
            }

          }

          function rwnEditPurchased_unlockButtons() {
            //unlock buttons
            var nEditPurchaseSubmit = $("#<%=btnEditPurchaseSubmit.ClientID%>");
            nEditPurchaseSubmit.removeAttr("disabled");
            var nEditPurchaseCancel = $("#<%=btnEditPurchaseCancel.ClientID%>");
            nEditPurchaseCancel.removeAttr("disabled");
          }

          function rwnEditPurchased_lockButtons() {
            //lock buttons
            var nEditPurchaseSubmit = $("#<%=btnEditPurchaseSubmit.ClientID%>");
            nEditPurchaseSubmit.attr("disabled", "disabled");
            var nEditPurchaseCancel = $("#<%=btnEditPurchaseCancel.ClientID%>");
            nEditPurchaseCancel.attr("disabled", "disabled");
          }

          function toggleGridFilterPanel(){

            $("#grid_filter_panel_elements").animate({ "height": "toggle" }, 500);

    //        if ($("#cphBody_MainContent_grid_filter_panel").height() == 10)
    //          $("#cphBody_MainContent_grid_filter_panel").height(165);
    //        else
    //          $("#cphBody_MainContent_grid_filter_panel").height(10);

              
    //        $("#cphBody_MainContent_grid_filter_panel").animate({ "height": "-=155px" }, 1000);

    //        $("#right").click(function () {
    //          $(".block").animate({ "left": "+=50px" }, "slow");
    //        });

    //        $("#cphBody_MainContent_grid_filter_panel").animate({
    //          height: "50px"
    //        }, 1000, function () {
    //          // Animation complete.
    //        });

          }

        </script>
      </telerik:RadCodeBlock>
    </asp:Content>

  13. J
    J avatar
    3 posts
    Member since:
    Feb 2015

    Posted 08 Feb 2015 in reply to J Link to this post

    And code behind...

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using FACS.RMS22.Entities;
    using FACS.RMS22.Entities.Model;
    using FACS.RMS22.Models;
    using System.Text;
    using System.Web.Services;
    using Telerik.Web.UI;
    using Telerik.Web.Data;

    namespace RMS.UI
    {
      public partial class PurchasedAndExceptionNumbers : RMSUIBasePage
      {
        #region [... fields / properties ...]

        enum GridFilterCheckBoxType { Region, ServiceType };

        private PurchasedAccommodationViewModel data;
        public PurchasedAccommodationViewModel Data
        {
          get
          {
            if (selectedServiceProviderId > 0)
            {
              //if (data == null) // jd: commented out to support changed requirement to drive filters by service provider
              //{
                data = new PurchasedAccommodationViewModel(serviceProviderId: selectedServiceProviderId);
              //}
            }
            else
            {
              data = new PurchasedAccommodationViewModel();
            }
            return (PurchasedAccommodationViewModel)data;
          }
        }

        private int totalPurchasedRecords
        {
          get
          {
            return PurchaseRecords.Count;
          }
        }

        private List<spPurchasedFacilitiesByServiceProviderList_Result> purchaseRecords;
        private List<spPurchasedFacilitiesByServiceProviderList_Result> PurchaseRecords
        {
          get
          {
            if (Data != null)
            {
              purchaseRecords = Data.LoadPurchasesRecord();

              //filter based on checkbox regions. if nothing selected (or only "All" selected), show all (don't filter)
              applyCheckBoxFilter(rcbFilterRegion, GridFilterCheckBoxType.Region);
              applyCheckBoxFilter(rcbFilterServiceType, GridFilterCheckBoxType.ServiceType);
              applyRangeFilter();

              #region [... TODO: JD: delete this when grid filter user preferences is finished ...]
              ////filter based on checkbox regions. if nothing selected (or only "All" selected), show all (don't filter)
              //if (rcbFilterRegion.CheckedItems.Count != 0 && (!rcbFilterRegion.Items[0].Checked))
              //{
              //  List<string> selectedRegions = new List<string>();
              //  foreach (RadComboBoxItem rcbi in rcbFilterRegion.CheckedItems)
              //  {
              //    selectedRegions.Add(rcbi.Value);
              //  }
              //  purchaseRecords = (List<spPurchasedFacilitiesByServiceProviderList_Result>)purchaseRecords.Where(s => selectedRegions.Contains(s.RegionId.ToString())).ToList();         
              //}

              ////filter based on checkbox service types. if nothing selected (or only "All" selected), show all (don't filter)
              //if (rcbFilterServiceType.CheckedItems.Count != 0 && (!rcbFilterServiceType.Items[0].Checked))
              //{
              //  List<string> selectedServiceTypes = new List<string>();
              //  foreach (RadComboBoxItem rcbi in rcbFilterServiceType.CheckedItems)
              //  {
              //    selectedServiceTypes.Add(rcbi.Value);
              //  }
              //  purchaseRecords = (List<spPurchasedFacilitiesByServiceProviderList_Result>)purchaseRecords.Where(s => selectedServiceTypes.Contains(s.ServiceTypeID.ToString())).ToList();
              //}
              #endregion

            }
            else
            {
              purchaseRecords = new List<spPurchasedFacilitiesByServiceProviderList_Result>();
            }
            return (List<spPurchasedFacilitiesByServiceProviderList_Result>)purchaseRecords;
          }
        }

        protected int selectedServiceProviderId
        {
          get
          {
            if (ViewState["selectedServiceProviderId"] == null)
            {
              int x = -1;
              try
              {
                x = Convert.ToInt32(Request.QueryString["id"].ToString());
              }
              catch (Exception ex1) { }

              ViewState["selectedServiceProviderId"] = x;
            }
            return (int)ViewState["selectedServiceProviderId"];
          }
          set
          {
            ViewState["selectedServiceProviderId"] = value;
          }
        }

        //protected List<RegionsList> AllRegions {
        //  get {
        //    if (ViewState["AllRegions"] == null) {
        //      ViewState["AllRegions"] = Data.RegionsList;
        //    }
        //    return (List<RegionsList>)ViewState["AllRegions"];
        //  }
        //}

        //protected List<ServiceType> AllServiceTypes {
        //  get {
        //    if (ViewState["AllServiceTypes"] == null) {
        //      ViewState["AllServiceTypes"] = Data.ServiceTypesList;
        //    }
        //    return (List<ServiceType>)ViewState["AllServiceTypes"];
        //  }
        //}

        //protected List<FundingType> AllFundingTypes {
        //  get {
        //    if (ViewState["AllFundingTypes"] == null) {
        //      ViewState["AllFundingTypes"] = Data.FundingTypesList;
        //    }
        //    return (List<FundingType>)ViewState["AllFundingTypes"];
        //  }
        //}

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {

          Page.Header.Controls.Add(
            new System.Web.UI.LiteralControl("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + ResolveUrl("~/App_Themes/PurchasedAndExceptionNumbers.css") + "\" />")
          );


          currentPageName = "PurchasedFacility_PurchasedAndExceptionNumbers".ToLower();
          if (!(Page.IsPostBack))
          {
            checkReferer(expectedRefererName: "PurchasedAndExceptionNumbers.aspx|RefMaint.aspx");
            buildMenuItems();
            bindData();
            hdnIsQuerying.Value = "1";
          }
        }

        #region [... grid handler ...]

        protected void rcbServiceProvider_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
          string[] preferredRegionIDs = {};
          string[] preferredServiceTypeIDs = {};

          selectedServiceProviderId = Convert.ToInt32(rcbServiceProvider.SelectedItem.Value);
          rdgPurchasedNumbers.Visible = true;

          spPurchasedFacilityPreferenceGet_Result pref = (spPurchasedFacilityPreferenceGet_Result)Data.GetFilterPreferences(myId, Convert.ToInt32(rcbServiceProvider.SelectedValue));
          if (pref != null)
          {
            checkBoxesFromArray(pref.RegionIds, rcbFilterRegion, pref);
            checkBoxesFromArray(pref.ServiceTypeIds, rcbFilterServiceType, pref);
            tbxPurchasedNumFrom.Value = pref.PurchaseNumberFrom;
            tbxPurchasedNumTo.Value = pref.PurchaseNumberTo;
          }

          rdgPurchasedNumbers.DataSource = purchaseRecords;
          rdgPurchasedNumbers.Rebind();
          lblUpdateResult.Visible = false;
          grid_filter_panel.Visible = true;
          
          //update page user prefs with updated service provider
          //if (IsPostBack)
          //{ 
            //load user prefs for filter panel (pass 0 for ServiceProvider to get the latest ServiceProvider selected)
            
          //spPurchasedFacilityPreferenceGet_Result pref = (spPurchasedFacilityPreferenceGet_Result)Data.GetFilterPreferences(myId, Convert.ToInt32(rcbServiceProvider.SelectedValue));
          //  if (pref != null)
          //  {
          //    checkBoxesFromArray(pref.RegionIds, rcbFilterRegion, pref);
          //    checkBoxesFromArray(pref.ServiceTypeIds, rcbFilterServiceType, pref);
          //    tbxPurchasedNumFrom.Value = pref.PurchaseNumberFrom;
          //    tbxPurchasedNumTo.Value = pref.PurchaseNumberTo;
          //  }
          
          //}
        }

        protected void bindData()
        {
          string[] preferredRegionIDs = {};
          string[] preferredServiceTypeIDs = {};

          rcbServiceProvider.DataSource = Data.ServiceProvidersList;
          rcbServiceProvider.DataTextField = "EntityName";
          rcbServiceProvider.DataValueField = "ServiceDeliveryID";
          rcbServiceProvider.DataBind();

          rcbFilterRegion.DataSource = Data.RegionsList;
          rcbFilterRegion.DataTextField = "Region";
          rcbFilterRegion.DataValueField = "RegionID";
          rcbFilterRegion.DataBind();

          rcbFilterServiceType.DataSource = Data.ServiceTypesList;
          rcbFilterServiceType.DataTextField = "ServiceTypeName";
          rcbFilterServiceType.DataValueField = "ServiceTypeId";
          rcbFilterServiceType.DataBind();

          //set user prefs for filter panel (pass 0 for ServiceProvider to get the latest ServiceProvider selected)
          spPurchasedFacilityPreferenceGet_Result pref = (spPurchasedFacilityPreferenceGet_Result)Data.GetFilterPreferences(myId, 0);
          selectedServiceProviderId = pref.ServiceProviderId;

          if (myReferer.ToLower().Contains("AddResPurchasedExceptionNumber.aspx".ToLower()) || myReferer.ToLower().Contains("UpdateResPurchaseExceptionNumber.aspx".ToLower()))
          {

          }
          
          rcbServiceProvider.SelectedValue = selectedServiceProviderId.ToString();
          //rcbServiceProvider_SelectedIndexChanged(this, new RadComboBoxSelectedIndexChangedEventArgs("","","",""));

          //set region and service type checkboxes from preferences
          if (pref != null)
          {
            checkBoxesFromArray(pref.RegionIds, rcbFilterRegion, pref);
            checkBoxesFromArray(pref.ServiceTypeIds, rcbFilterServiceType, pref);
          }

          applyRangeFilter();
          rdgPurchasedNumbers.DataSource = PurchaseRecords;
          rdgPurchasedNumbers.DataBind();

          if (rcbServiceProvider.SelectedIndex == 0)
          {
            // hide grid
            rdgPurchasedNumbers.Visible = false;
          }

          lblError.Text = string.Empty;

          //rdpPurchasedDate.SelectedDate = DateTime.Now;
          //rdpPurchasedDate.MaxDate = DateTime.Now;
          hdnUserId.Value = myId.ToString();
        }

        protected void rdgPurchasedNumbers_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
          rdgPurchasedNumbers.DataSource = PurchaseRecords;
        }

        protected void rdgPurchasedNumbers_DetailTableDataBind(object source, Telerik.Web.UI.GridDetailTableDataBindEventArgs e)
        {
          GridDataItem dataItem = (GridDataItem)e.DetailTableView.ParentItem;
          int gid = Convert.ToInt32(dataItem.GetDataKeyValue("PurchasedFacilityGroupId").ToString());
          e.DetailTableView.DataSource = new PurchasedAccommodationViewModel().GetPurchaseHistory(groupId: gid);
        }

        protected void rdgPurchasedNumbers_ItemDataBound_parent(RadGrid grid, Telerik.Web.UI.GridItemEventArgs e)
        {
          if (e.Item is GridDataItem)
          {
            GridDataItem item = (GridDataItem)e.Item;

            Label x;
            Label y;
            x = (Label)item.FindControl("lblTotalPurchased");
            y = (Label)item.FindControl("lblTotalOccupied");

            try
            {
              if (((Convert.ToInt32(x.Text)) - (Convert.ToInt32(y.Text))) <= 0)
              {
                x.Style.Add("color", "#FF0000");
              }
            }
            catch (Exception ex1) { }

            LinkButton ledit = (LinkButton)item.FindControl("lkbEdit");
            LinkButton lview = (LinkButton)item.FindControl("lkbDetail");

            spPurchasedFacilitiesByServiceProviderList_Result dat = (spPurchasedFacilitiesByServiceProviderList_Result)item.DataItem;

            try
            {
              int groupId = (int)dat.PurchasedFacilityGroupId;

              int serviceProviderId = (int)dat.ServiceProviderId;
              string providerName = rcbServiceProvider.FindItemByValue(serviceProviderId.ToString()).Text;

              int regionId = (int)dat.RegionId;
              string regionName = dat.Region;

              int serviceTypeId = (int)dat.ServiceTypeID;
              string serviceType = dat.ServiceType;

              int fundingTypeId = (int)dat.FundingTypeId;
              string fundingType = dat.FundingTypeName;

              int? currentPurchased = -1;
              if (dat.TotalPurchased.HasValue)
              {
                currentPurchased = dat.TotalPurchased;
              }

              int currentUsed = dat.BeingOccupied.HasValue ? (int)dat.BeingOccupied : 0;
              int minValue = 0;
              if ((int)currentPurchased > 0)
              {
                if ((int)currentPurchased <= currentUsed)
                {
                  minValue = currentUsed - (int)currentPurchased;
                }
              }

              //double? costPerDay = -1;

              //if (dat.CostPerDay.HasValue) {
              //  costPerDay = (double)dat.CostPerDay;
              //}

              //string tstr = string.Format("return EditPurchaseRecord('{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}');", groupId, serviceProviderId, regionId, serviceTypeId, fundingTypeId, currentPurchased, currentUsed, (double)costPerDay, minValue, providerName, regionName, serviceType, fundingType);
              string tstr = string.Format("return EditPurchaseRecord('{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}');", groupId, serviceProviderId, regionId, serviceTypeId, fundingTypeId, currentPurchased, currentUsed, minValue, providerName, regionName, serviceType, fundingType);
              ledit.Attributes.Add("OnClick", tstr);

              //dont' show edit link for FundingType = Exception
              if (dat.FundingTypeName == "Exception")
              {
                ledit.Text = "";
              }

              tstr = string.Format("return ViewHistory({0});", ((HiddenField)item.FindControl("hdnPurchasedGroupId")).Value);
              lview.Attributes.Add("OnClick", tstr);
            }
            catch (Exception ex1)
            {
              if (ledit != null)
              {
                ledit.Enabled = false;
              }
              if (lview != null)
              {
                lview.Enabled = false;
              }
            }

            try
            {
              //if (dat.CostPerDay == null) {
              //  ((Label)item.FindControl("lblCostPerDay")).Text = "&nbsp;";
              //}
              if ((int)dat.BeingOccupied == 0)
              {
                ((Label)item.FindControl("lblTotalOccupied")).Text = "&nbsp;";
              }
            }
            catch (Exception ex) { }
          }
          else if (e.Item is GridFilteringItem)
          {

            GridTableView tv = grid.MasterTableView;

            Dictionary<string, string> flExpr = new Dictionary<string, string>();

            RadComboBox rRegion = (RadComboBox)e.Item.FindControl("rcbFilterRegion");
            if (rRegion != null)
            {
              if (rRegion.Items.Count <= 1)
              {
                rRegion.DataSource = new LookupDataViewModel().GetRegion();
                rRegion.DataBind();

                rRegion.FindItemByText("Helpline").Remove();
              }
            }

            RadComboBox rFundingType = (RadComboBox)e.Item.FindControl("rcbFilterFundingType");
            if (rFundingType != null)
            {
              if (rFundingType.Items.Count <= 1)
              {
                rFundingType.DataSource = new LookupDataViewModel().GetFundingTypes();
                rFundingType.DataBind();
              }
            }

            List<spUserPreferencesGet_Result> g1 = new List<spUserPreferencesGet_Result>();
            try
            {
              g1 = (PagePreferences).Where(w => w.GridName.ToLower() == grid.ID.ToLower()).ToList();
            }
            catch (Exception ex1)
            {
              return;
            }

            RadComboBox rServiceType = (RadComboBox)e.Item.FindControl("rcbFilterServiceType");
            if (rServiceType != null)
            {
              if (rServiceType.Items.Count <= 1)
              {
                rServiceType.DataSource = new LookupDataViewModel().ServiceTypes;
                rServiceType.DataBind();
              }
            }

            string filterValue = string.Empty;
            string f = string.Empty;

            foreach (spUserPreferencesGet_Result u in g1.Where(w => (!(string.IsNullOrWhiteSpace(w.FilterKey)))).OrderBy(o => o.UserPreferenceId).ToList())
            {
              if (!(string.IsNullOrEmpty(u.FilterKey)))
              {

                hasFilter = true;

                switch (u.ColumnName.ToLower())
                {
                  case "region":
                    hasFilter = true;

                    if (!(string.IsNullOrWhiteSpace(f)))
                    {
                      f += "AND [Region]='" + u.FilterValue + "'";
                    }
                    else
                    {
                      f = "([Region]='" + u.FilterValue + "'";
                    }

                    if (!(string.IsNullOrWhiteSpace(u.FilterValue)))
                    {
                      rRegion.FindItemByText(u.FilterValue).Selected = true;
                    }

                    break;
                  case "fundingtypename":
                    hasFilter = true;

                    if (!(string.IsNullOrWhiteSpace(f)))
                    {
                      f += "AND [FundingTypeName]='" + u.FilterValue + "'";
                    }
                    else
                    {
                      f = "([FundingTypeName]='" + u.FilterValue + "'";
                    }

                    filterValue = string.Empty;
                    if (!(string.IsNullOrWhiteSpace(u.FilterValue)))
                    {
                      rFundingType.FindItemByText(u.FilterValue).Selected = true;
                    }

                    break;
                  case "servicetype":
                    hasFilter = true;

                    if (!(string.IsNullOrWhiteSpace(f)))
                    {
                      f += "AND [ServiceType]='" + u.FilterValue + "'";
                    }
                    else
                    {
                      f = "([ServiceType]='" + u.FilterValue + "'";
                    }

                    //filterValue = string.Empty;

                    if (!(string.IsNullOrWhiteSpace(u.FilterValue)))
                    {
                      rServiceType.FindItemByText(u.FilterValue).Selected = true;
                    }

                    break;
                  default:
                    break;
                }
              }
            }
            if (!(string.IsNullOrWhiteSpace(f)))
            {
              f += ")";
              grid.MasterTableView.FilterExpression = f;
            }
            //}
          }
        }

        bool hasFilter = false;

        protected void rdgPurchasedNumbers_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
          RadGrid grid = (RadGrid)sender;
          if (e.Item is GridDataItem)
          {
            GridDataItem item = (GridDataItem)e.Item;
            if (item.OwnerTableView.Name == "PurchasedHistory")
            {
              return;
            }
            else if (item.OwnerTableView.Name == "LatestPurchased")
            {
              rdgPurchasedNumbers_ItemDataBound_parent(grid: grid, e: e);
            }
          }
          else if (e.Item is GridFilteringItem)
          {
            GridFilteringItem item = (GridFilteringItem)e.Item;
            if (item.OwnerTableView.Name == "PurchasedHistory")
            {
              return;
            }
            else if (item.OwnerTableView.Name == "LatestPurchased")
            {
              rdgPurchasedNumbers_ItemDataBound_parent(grid: grid, e: e);
            }
          }
        }

        protected void rcbServiceProvider_SelectedIndexChanged(object sender, EventArgs e) { }

        protected string BuildResidentialAPurchaseNumberViewUrl(int PurchasedNumberId, int ServiceProviderId, string upddel)
        {
          return string.Format("~/Residential/UpdateResPurchaseExceptionNumber.aspx?id={0}&spid={1}&upddel={2}", PurchasedNumberId, ServiceProviderId, upddel);
        }

        protected string BuildComment(object param)
        {
          if (param == null)
          {
            return "Comment: n/a";
          }
          else
          {
            return string.Format("Comment:\n{0}", param.ToString().Trim());
          }
        }

        protected string BuildCommentPreview(object param)
        {
          if (param == null)
          {
            return "";
          }
          else
          {
            if (param.ToString().Trim().Length > 45)
            {
              return string.Format("{0}...", param.ToString().Trim().Substring(0, 45));
            }
            else
            {
              return string.Format("{0}", param.ToString().Trim());
            }

          }
        }

        #endregion

        #region [... add / edit ...]

        private void loadExistingRecord(int selectedId)
        {
        }

        protected void bindEditForm(int selectedId)
        {
          loadExistingRecord(selectedId: selectedId);
        }

        protected bool ShowDeleteOption(int totalUsed)
        {
          return totalUsed > 0 ? false : true;
        }

        /// <summary>
        /// groupId, newPurchased, newDate
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="newPurchasedNumber"></param>
        /// <param name="newDate"></param>
        /// <returns></returns>
        [WebMethod]
        public static string SaveNewPurchase(object groupId, object newPurchasedNumber, object newDate, object uid, object comment)
        {
          //public static string SaveNewPurchase(object groupId, object newPurchasedNumber, object newDate, object uid, object newCost, object comment) {
          string returnValue = "";

          int? g = null;
          int? p = null;
          DateTime? d = null;
          int? u = null;
          decimal? c = null;

          bool valid = true;

          try
          {
            g = Convert.ToInt32(groupId);
          }
          catch (Exception ex1)
          {
            returnValue += "Invalid Group Id parameter.\n";
            valid = false;
          }

          try
          {
            p = Convert.ToInt32(newPurchasedNumber);
          }
          catch (Exception ex2)
          {
            returnValue += "Invalid Purchased Number.\n";
            valid = false;
          }

          try
          {
            d = Convert.ToDateTime(newDate);
          }
          catch (Exception ex3)
          {
            returnValue += "Invalid Date Purchased.\n";
            valid = false;
          }

          try
          {
            u = Convert.ToInt32(uid);
          }
          catch (Exception ex)
          {
            returnValue += "Invalid User Id.\n";
            valid = false;
          }

          //try {
          //  if (!(string.IsNullOrWhiteSpace(newCost.ToString()))) {
          //    c = Convert.ToDecimal(newCost);
          //  }
          //} catch (Exception ex4) {
          //}

          string cmt = string.Empty;
          try
          {
            cmt = comment.ToString().Trim().Replace(Environment.NewLine, "&lt;br /&gt;");
          }
          catch (Exception ex1) { }

          if (valid)
          {
            try
            {
              //spPurchasedFacilitiesAdd_Result result = new PurchasedAccommodationViewModel().Update(groupId: (int)g, datePurchased: (DateTime)d, newPurchasedNumber: (int)p, comment: cmt, userId: (int)u);
              spPurchasedFacilitiesAdd_Result result = new PurchasedAccommodationViewModel().Update(groupId: (int)g, newPurchasedNumber: (int)p, comment: cmt, userId: (int)u);
              //returnValue = string.Format("gid_{0},total_{1},used_{2},cost_{3}", result.GroupId, result.AllPurchasedNumber, result.AllUsedNumber, result.CurrentCostPerDay);
              returnValue = string.Format("gid_{0},total_{1},used_{2}", result.GroupId, result.AllPurchasedNumber, result.AllUsedNumber);
            }
            catch (Exception ex1)
            {

              if (ex1.InnerException.ToString().ToLower().IndexOf("validation failure") > -1)
                returnValue = ex1.InnerException.Message;
              else
                returnValue = ex1.Message;

            }
          }

          return returnValue;
        }

        protected void rebindGrid()
        {
          rdgPurchasedNumbers.Rebind();
        }

        //protected static string CostPerDayFormatter(object param) {
        //  if (param == null) {
        //    return "&#8212";
        //  } else {
        //    try {
        //      return string.Format("{0:C2}", Convert.ToDecimal(param));
        //    } catch (Exception ex1) {
        //      return "&#8212";
        //    }
        //  }
        //}

        #endregion

        #region [... grid with combo filtering ...]

        protected void RadGridWithComboFiltering_ItemCommand(object sender, GridCommandEventArgs e)
        {
          RadGrid grid = (Telerik.Web.UI.RadGrid)sender;

          #region [... page index ...]

          if (e.CommandName == Telerik.Web.UI.RadGrid.PageCommandName)
          {
            pageIndexChanged = true;
          }

          #endregion

          #region [... page size ...]

          if (e.CommandName == "ChangePageSize")
          {
            isShowAll = ((Telerik.Web.UI.GridPageSizeChangedEventArgs)(e)).NewPageSize > 100 ? true : false;
            pageSizeChanged = true;
            RebindGrid(grid: grid);
          }

          #endregion

        }

        bool pageIndexChanged = false;
        bool pageSizeChanged = false;

        protected void rdgPurchasedNumbers_preRender(object sender, System.EventArgs e)
        {
          if (!(Page.IsPostBack))
          {
            //rdgPurchasedNumbers.MasterTableView.Items[0].Expanded = true;
            //rdgPurchasedNumbers.MasterTableView.Items[0].ChildItem.NestedTableViews[0].Items[0].Expanded = true;
          }

          // do filtering
          List<spUserPreferencesGet_Result> g1 = new List<spUserPreferencesGet_Result>();
          RadGrid grid = (RadGrid)sender;

          #region [... page size ...]

          if (pageSizeChanged)
          {
            pageSizePreference_helper(grid: grid, newSize: grid.PageSize);
          }

          #endregion

          #region [... page index ...]

          if (pageIndexChanged)
          {
            spUserPreferencesGet_Result x = PagePreferences.Where(w => w.CurrentPageNumber.HasValue &&
                                                       w.PageName.ToLower() == currentPageName.ToLower() &&
                                                       w.GridName.ToLower() == grid.ID.ToString().ToLower()).FirstOrDefault();
            if (x != null)
            {
              x.CurrentPageNumber = grid.CurrentPageIndex + 1;
              new UserPreferenceViewModel(userId: myId, userName: string.Empty).UpdatePreference(userPreference: x);
            }
            else
            {
              new UserPreferenceViewModel(userId: myId, userName: string.Empty).AddPreference(new spUserPreferencesGet_Result
              {
                UserId = myId,
                PageName = currentPageName.ToLower(),
                GridName = grid.ID.ToLower(),
                ColumnName = string.Empty,
                FilterKey = string.Empty,
                FilterValue = string.Empty,
                OrderBy = string.Empty,
                CurrentPageNumber = grid.CurrentPageIndex + 1,
                CurrentPageSize = null
              });

            }

            ViewState["mypreference"] = null;
          }

          #endregion

          g1 = (from x in PagePreferences where x.GridName.ToLower() == grid.ID.ToLower() select x).ToList();

          if (g1.Count > 0)
          {

            bool anyPreference = false;

            #region [... page size ...]
            // sometime recorded preference page size in full, but data refreshed over than the size recorded.
            // so, check grid total items again and reset page size.

            // page size
            object pz = g1.Where(w => (w.CurrentPageSize.HasValue)).Select(s => s.CurrentPageSize).FirstOrDefault();
            int pzi = 100;

            if (pz != null)
            {
              try
              {
                pzi = Convert.ToInt32(pz);

                if (GridDataSourceItemsCount.HasValue)
                {
                  if ((int)GridDataSourceItemsCount > pzi)
                  {
                    pzi = (int)GridDataSourceItemsCount;
                    pageSizePreference_helper(grid: grid, newSize: pzi);
                  }
                }

                grid.PageSize = pzi;
                anyPreference = true;
              }
              catch (Exception ex1) { }
            }

            #endregion

            #region [... paging ...]

            // paging
            pz = g1.Where(w => (w.CurrentPageNumber.HasValue)).Select(s => s.CurrentPageSize).FirstOrDefault();
            object pzz = g1.Where(w => (w.CurrentPageNumber.HasValue)).Select(s => s.CurrentPageNumber).FirstOrDefault();

            if (pzz == null)
            {
              pzi = 1;
            }
            else
            {
              pzi = (int)pzz;
            }

            if ((pz == null) || (string.IsNullOrWhiteSpace(pz.ToString())))
            {
              pz = "100";
            }

            try
            {
              grid.PageSize = Convert.ToInt32(pz);
              grid.CurrentPageIndex = pzi;
              anyPreference = true;
            }
            catch (Exception ex1) { }

            #endregion

            #region [... sorting ...]

            // sorting
            foreach (spUserPreferencesGet_Result u in g1.Where(w => (!(string.IsNullOrWhiteSpace(w.OrderBy)))).OrderBy(o => o.UserPreferenceId).ToList())
            {
              if (!(string.IsNullOrEmpty(u.OrderBy)))
              {
                grid.MasterTableView.SortExpressions.AddSortExpression(new GridSortExpression
                {
                  FieldName = u.ColumnName,
                  SortOrder = u.OrderBy.ToLower() == "ascending" ? GridSortOrder.Ascending : GridSortOrder.Descending
                });
                anyPreference = true;
              }
            }

            #endregion

            #region [... filtering ...]

            if (hasFilter)
            {
              string ff = grid.MasterTableView.FilterExpression;
              anyPreference = true;
            }

            #endregion

            if (anyPreference)
            {
              RebindGrid(grid: grid);
            }

          }

          //// merge District cells
          //for (int rowIndex = rdgPurchasedNumbers.Items.Count - 2; rowIndex >= 0; rowIndex--)
          //{
          //  GridDataItem row = rdgPurchasedNumbers.Items[rowIndex];
          //  GridDataItem previousRow = rdgPurchasedNumbers.Items[rowIndex + 1];

          //  for (int i = 0; i < row.Cells.Count; i++)
          //  {
          //    if (row.Cells[i].Text == previousRow.Cells[i].Text)
          //    {
          //      //row.Cells[i].RowSpan = previousRow.Cells[i].RowSpan < 2 ? 2 : previousRow.Cells[i].RowSpan + 1;
          //      //previousRow.Cells[i].Visible = false;
          //    }
          //  }
          //}    

        }

        #endregion


        private void buildMenuItems()
        {
          RMS22 ms = (RMS22)base.Master;

          HyperLink h1 = ms.SubMenuItem01;
          h1.Visible = true;
          h1.Enabled = true;
          h1.NavigateUrl = (string.Format("~/RefMaint/RefMaint.aspx"));
          h1.Text = "Back to Main";

          HyperLink h2 = ms.SubMenuItem02;
          h2.Visible = false;
          h2.Enabled = false;
          h2.NavigateUrl = "";
          h2.Text = "";

          HyperLink h3 = ms.SubMenuItem03;
          h3.Visible = false;
          h3.Enabled = false;
          h3.NavigateUrl = "";
          h3.Text = "";

          HyperLink h4 = ms.SubMenuItem04;
          h4.Visible = false;
          h4.Enabled = false;
          h4.NavigateUrl = "";
          h4.Text = "";

          HyperLink h5 = ms.SubMenuItem05;
          h5.Visible = false;
          h5.Enabled = false;
          h5.NavigateUrl = "";
          h5.Text = "";

          HyperLink h6 = ms.SubMenuItem06;
          h6.Visible = false;
          h6.Enabled = false;
          h6.NavigateUrl = "";
          h6.Text = "";

          HyperLink h7 = ms.SubMenuItem07;
          h7.Visible = false;
          h7.Enabled = false;
          h7.NavigateUrl = "";
          h7.Text = "";
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
          rdgPurchasedNumbers.DataSource = PurchaseRecords;
          rdgPurchasedNumbers.DataBind();

          spPurchasedFacilityPreferenceUpdate_Result result = new PurchasedAccommodationViewModel().UpdateFilterPreferences(
            userId: myId, serviceProviderId: selectedServiceProviderId, 
            regionIds: getCSVsFromCheckBoxes(rcbFilterRegion),
            serviceTypeIds: getCSVsFromCheckBoxes(rcbFilterServiceType), 
            purchaseNumberFrom: tbxPurchasedNumFrom.Value == null ? -1 : (int)tbxPurchasedNumFrom.Value,
            purchaseNumberTo: tbxPurchasedNumTo.Value == null ? -1 : (int)tbxPurchasedNumTo.Value);
        }

        private string getCSVsFromCheckBoxes(RadComboBox rcbCheckBoxes) 
        {
          string csvIds = "";
          if (rcbCheckBoxes.CheckedItems.Count > 0)
          {
            foreach (RadComboBoxItem rcbi in rcbCheckBoxes.CheckedItems)
            {
              csvIds += rcbi.Value + ",";
            }
            csvIds = csvIds.TrimEnd(',');
          }
          return csvIds;
        }

        private void applyCheckBoxFilter(RadComboBox rcbFilter, GridFilterCheckBoxType filterType)
        {
          //filter based on checkbox regions. if nothing selected (or only "All" selected), show all (don't filter)
          if (rcbFilter.CheckedItems.Count != 0 && (!rcbFilter.Items[0].Checked))
          {
            List<string> selectedIDs = new List<string>();
            foreach (RadComboBoxItem rcbi in rcbFilter.CheckedItems)
            {
              selectedIDs.Add(rcbi.Value);
            }
            purchaseRecords = (List<spPurchasedFacilitiesByServiceProviderList_Result>)purchaseRecords.Where(s => selectedIDs.Contains(
              filterType == GridFilterCheckBoxType.ServiceType ? s.ServiceTypeID.ToString() : s.RegionId.ToString())).ToList();
          }
        }

        private void applyRangeFilter()
        {
          if (tbxPurchasedNumFrom.Value != null)
          {
            purchaseRecords = (List<spPurchasedFacilitiesByServiceProviderList_Result>)purchaseRecords.Where(s => s.TotalPurchased >= tbxPurchasedNumFrom.Value).ToList();
          }
          if (tbxPurchasedNumTo.Value != null)
          {
            purchaseRecords = (List<spPurchasedFacilitiesByServiceProviderList_Result>)purchaseRecords.Where(s => s.TotalPurchased <= tbxPurchasedNumTo.Value).ToList();
          }
        }

        protected void checkBoxesFromArray(string csvValues, RadComboBox rcbCheckBoxes, spPurchasedFacilityPreferenceGet_Result pref)
        {
          string[] idArray = { };

          //1st uncheck existing boxes
          rcbCheckBoxes.ClearCheckedItems();
          foreach (RadComboBoxItem rcbi in rcbCheckBoxes.Items)
            rcbi.Checked = false;

          if (csvValues != string.Empty)
          {
            //set checked checkboxes from preferences
            idArray = csvValues.Split(',');
           
            foreach (RadComboBoxItem rcbi in rcbCheckBoxes.Items)
            {
              if (idArray.Where(r => r == rcbi.Value).Count() > 0)
              {
                rcbi.Checked = true;
              }
            }
          }
        }

      }
    }
  14. Maria Ilieva
    Admin
    Maria Ilieva avatar
    4017 posts

    Posted 11 Feb 2015 Link to this post

    Hi,

    Can I kindly ask you to disable the Ajax and see what the result in this case would be?
    Based on the big amount of client code and Ajax settings I would suggest that some js error appear on the page and this breaks the RadComboBox to behaves correctly. Can you please inspect the request using the browser's console and see if any errors appear.

    Regards,
    Maria Ilieva
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
Back to Top
UI for ASP.NET Ajax is Ready for VS 2017