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

Filtering Issues

4 Answers 116 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Mike
Top achievements
Rank 1
Mike asked on 26 Jan 2016, 09:51 PM

I have a grid and I'm trying to add some date range filtering to.  The date range filter is on a GridDateTimeColumn, however I just need to filter on Date.  I enabled Range Filtering on the column, but the filter control didn't play nice with the grid, it extendes the width of the DateTimeColumn so the other columns are almost too small.  I then implemented a FilterTemplate with two Telerik DatePicker controls (one on top of the other) as per this demo and that seemed to work.  However, it broke other filtering that I had on the grid. 

Whenever I use any other filter, the date range filter is ignored. 

Example workflow:

  1. Enter From Date and To Date - note the records in the grid
  2. Filter on any other column - note the date range is ignored

Here is my markup 

<%@ Page Title="" Language="C#" MasterPageFile="~/pqc.Master" AutoEventWireup="true" CodeBehind="inspection.aspx.cs" Inherits="pqc.web.inspection.Inspection" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="head1" runat="server">
    <telerik:RadScriptBlock runat="server" ID="radScriptBlock">
        <script type="text/javascript">
            function RowSelected(sender, args) {
                var key = args.getDataKeyValue("inspection_id");
                if (key) {
                    window.location.href = "viewinspection.aspx?id=" + key;
                }
            }
        </script>
    </telerik:RadScriptBlock>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContextMenu" runat="server">
    <div>
        <telerik:RadButton runat="server" ID="radNew" Text="New Inspection" OnClick="radNew_OnClick"></telerik:RadButton>
    </div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
    <telerik:RadAjaxManager runat="server" ID="radAjaxManager" EnableAJAX="True">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="radInspection">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="radInspection" LoadingPanelID="radLpInspection" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
    <div class="title">Inspection</div>
    <telerik:RadAjaxLoadingPanel runat="server" ID="radLpInspection"></telerik:RadAjaxLoadingPanel>
    <telerik:RadGrid runat="server" ID="radInspection" AllowPaging="True" AllowSorting="True" ShowHeader="True" GridLines="None" CellPadding="0" CellSpacing="0"
        PageSize="20" AllowFilteringByColumn="True" OnNeedDataSource="radInspection_OnNeedDataSource" OnItemCommand="radInspection_OnItemCommand"
        OnItemDataBound="radInspection_OnItemDataBound">
        <ClientSettings AllowColumnsReorder="False" EnableRowHoverStyle="True" EnablePostBackOnRowClick="False">
            <Selecting AllowRowSelect="True"></Selecting>
            <Scrolling UseStaticHeaders="True"></Scrolling>
            <ClientEvents OnRowSelected="RowSelected"></ClientEvents>
        </ClientSettings>
        <GroupingSettings CaseSensitive="False"></GroupingSettings>
        <MasterTableView DataKeyNames="inspection_id" ClientDataKeyNames="inspection_id" AutoGenerateColumns="False" AllowMultiColumnSorting="True" EnableHeaderContextMenu="True"
            AllowFilteringByColumn="True" CommandItemDisplay="TopAndBottom" Height="100%">
            <NoRecordsTemplate>No inspections.</NoRecordsTemplate>
            <CommandItemSettings ShowAddNewRecordButton="False" ShowCancelChangesButton="False" ShowSaveChangesButton="False" ShowRefreshButton="True"></CommandItemSettings>
            <Columns>
                <telerik:GridBoundColumn DataField="inspection_id" HeaderText="ID">
                    <HeaderStyle Width="1%" VerticalAlign="Top" HorizontalAlign="Right"></HeaderStyle>
                    <ItemStyle Width="1%" VerticalAlign="Top" HorizontalAlign="Right"></ItemStyle>
                    <FilterTemplate>
                        <asp:ImageButton runat="server" ID="ibClearDate" ImageUrl="images/icons/cancel.png" AlternateText="Clear filter" ToolTip="Clear filter"
                            Width="16" Height="16" OnClick="ibClearDate_OnClick" />
                    </FilterTemplate>
                </telerik:GridBoundColumn>
                <telerik:GridDateTimeColumn DataField="inspection_datetime" HeaderText="Inspection Date" EnableTimeIndependentFiltering="False"
                    PickerType="DateTimePicker" DataFormatString="{0:yyyy-MM-dd HH:mm tt}" UniqueName="InspectionDate" enable>
                    <ItemStyle Width="7%" VerticalAlign="Top" HorizontalAlign="Left"></ItemStyle>
                    <HeaderStyle Width="7%"></HeaderStyle>
                    <FilterTemplate>
                        <div style="float: left">
                            <telerik:RadDatePicker runat="server" ID="radFromInspectionDate" Width="110px">
                                <Calendar>
                                    <SpecialDays>
                                        <telerik:RadCalendarDay Repeatable="Today">
                                            <ItemStyle BackColor="LightGray" Font-Bold="True" BorderStyle="Solid" BorderColor="Black" BorderWidth="1px"></ItemStyle>
                                        </telerik:RadCalendarDay>
                                    </SpecialDays>
                                </Calendar>
                                <DateInput DisplayDateFormat="yyyy-MM-dd" DateFormat="yyyy-MM-dd" EmptyMessage="From Date"></DateInput>
                                <ClientEvents OnDateSelected="FromInspectionDateSelected"></ClientEvents>
                            </telerik:RadDatePicker>
                            <br />
                            <telerik:RadDatePicker runat="server" ID="radToInspectionDate" Width="110px">
                                <Calendar>
                                    <SpecialDays>
                                        <telerik:RadCalendarDay Repeatable="Today">
                                            <ItemStyle BackColor="LightGray" Font-Bold="True" BorderStyle="Solid" BorderColor="Black" BorderWidth="1px"></ItemStyle>
                                        </telerik:RadCalendarDay>
                                    </SpecialDays>
                                </Calendar>
                                <DateInput DisplayDateFormat="yyyy-MM-dd" DateFormat="yyyy-MM-dd" EmptyMessage="To Date"></DateInput>
                                <ClientEvents OnDateSelected="ToInspectionDateSelected"></ClientEvents>
                            </telerik:RadDatePicker>
                        </div>
                        <telerik:RadScriptBlock runat="server" ID="radInspectionScripts">
                            <script type="text/javascript">
                                function FromInspectionDateSelected(sender, args) {
                                    var tableView = $find("<%# Container.OwnerTableView.ClientID %>");
                                    var toPicker = $find('<%# Container.FindControl("radToInspectionDate").ClientID %>');
                                    if (tableView && toPicker) {
                                        var fromDate = FormatSelectedDate(sender);
                                        var toDate = FormatSelectedDate(toPicker);
                                        tableView.filter("InspectionDate", fromDate + " " + toDate, "Between");
                                    }
                                }
                                function ToInspectionDateSelected(sender, args) {
                                    var tableView = $find("<%# Container.OwnerTableView.ClientID %>");
                                    var fromPicker = $find('<%# Container.FindControl("radFromInspectionDate").ClientID %>');
                                    if (tableView && fromPicker) {
                                        var fromDate = FormatSelectedDate(fromPicker);
                                        var toDate = FormatSelectedDate(sender);
                                        tableView.filter("InspectionDate", fromDate + " " + toDate, "Between");
                                    }
                                }
                                function FormatSelectedDate(picker) {
                                    if (picker) {
                                        var date = picker.get_selectedDate();
                                        var dateInput = picker.get_dateInput();
                                        if (!date) {
                                            date = new Date();
                                        }
                                        var formattedDate = dateInput.get_dateFormatInfo().FormatDate(date, dateInput.get_displayDateFormat());
                                        return formattedDate;
                                    }
                                    return null;
                                }
                            </script>
                        </telerik:RadScriptBlock>
                    </FilterTemplate>
                </telerik:GridDateTimeColumn>
                <telerik:GridBoundColumn DataField="inspector" HeaderText="Inspector" FilterControlWidth="75%">
                    <HeaderStyle Width="7%"></HeaderStyle>
                    <ItemStyle Width="7%" VerticalAlign="Top" HorizontalAlign="Left"></ItemStyle>
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="division" HeaderText="Division" UniqueName="Division" FilterControlWidth="75%">
                    <HeaderStyle Width="5%"></HeaderStyle>
                    <ItemStyle Width="5%" VerticalAlign="Top" HorizontalAlign="Left"></ItemStyle>
                    <FilterTemplate>
                        <telerik:RadComboBox runat="server" ID="radDivisionFilter" Width="120px" OnClientSelectedIndexChanged="DivisionIndexChanged"></telerik:RadComboBox>
                        <telerik:RadCodeBlock runat="server" ID="radDivisionCode">
                            <script type="text/javascript">
                                function DivisionIndexChanged(sender, args) {
                                    var tableView = $find("<%# Container.OwnerTableView.ClientID %>");
                                    tableView.filter("Division", args.get_item().get_value(), "EqualTo");
                                }
                            </script>
                        </telerik:RadCodeBlock>
                    </FilterTemplate>
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="full_grade" HeaderText="Grade" FilterControlWidth="75%">
                    <HeaderStyle Width="8%"></HeaderStyle>
                    <ItemStyle Width="8%" VerticalAlign="Top" HorizontalAlign="Left"></ItemStyle>
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="tag_number" HeaderText="Tag #" FilterControlWidth="75%">
                    <HeaderStyle Width="5%"></HeaderStyle>
                    <ItemStyle Width="5%" VerticalAlign="Top" HorizontalAlign="Left"></ItemStyle>
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="size_description" HeaderText="Width" FilterControlWidth="75%">
                    <HeaderStyle Width="4%"></HeaderStyle>
                    <ItemStyle Width="4%" VerticalAlign="Top" HorizontalAlign="Left"></ItemStyle>
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="length_description" HeaderText="Length" FilterControlWidth="75%">
                    <HeaderStyle Width="4%"></HeaderStyle>
                    <ItemStyle Width="4%" VerticalAlign="Top" HorizontalAlign="Left"></ItemStyle>
                </telerik:GridBoundColumn>
                <telerik:GridCheckBoxColumn DataField="complete" HeaderText="Completed" AllowFiltering="False">
                    <HeaderStyle Width="2%" HorizontalAlign="Right"></HeaderStyle>
                    <ItemStyle Width="2%" VerticalAlign="Top" HorizontalAlign="Right"></ItemStyle>
                </telerik:GridCheckBoxColumn>
            </Columns>
        </MasterTableView>
    </telerik:RadGrid>
</asp:Content>

Here is my code-behind 

using System;
using System.Web.UI;
using pqc.web.Classes;
using Telerik.Web.UI;
 
namespace pqc.web.inspection
{
  public partial class Inspection : PageBase
  {
    private DateTime? FromDate { get; set; }
 
    private DateTime? ToDate { get; set; }
 
    protected void Page_Load(object sender, EventArgs e)
    {
      if (Session["Key"] != null)
      {
        Session["Key"] = -1;
      }
      if (!IsPostBack)
      {
        LoadData();
      }
    }
 
    private void LoadData()
    {
      var inspections = dal.Inspection.GetVInspectionHeaders();
      radInspection.DataSource = inspections;
    }
 
    protected void radInspection_OnNeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
      LoadData();
    }
 
    protected void radNew_OnClick(object sender, EventArgs e)
    {
      Session["Key"] = -1;
      Response.Redirect("header.aspx");
    }
 
    protected void radInspection_OnItemCommand(object sender, GridCommandEventArgs e)
    {
      var grid = sender as RadGrid;
      if (grid == null)
      {
        return;
      }
      if (e.CommandName == "RowClick")
      {
        var item = e.Item as GridEditableItem;
        if (item == null)
        {
          return;
        }
        var key = item.GetDataKeyValue("inspection_id").ToString();
        Response.Redirect(string.Format("viewinspection.aspx?id={0}", key));
      }
      else
      {
        var filtering = e.Item as GridFilteringItem;
        if (filtering == null)
        {
          return;
        }
        var selected = "";
        var fromDate = filtering.FindControl("radFromInspectionDate") as RadDatePicker;
        var toDate = filtering.FindControl("radToInspectionDate") as RadDatePicker;
        if (fromDate != null)
        {
          if (!string.IsNullOrEmpty(grid.MasterTableView.GetColumn("InspectionDate").CurrentFilterValue))
          {
            selected = grid.MasterTableView.GetColumn("InspectionDate").CurrentFilterValue;
            selected = selected.Split(' ')[0];
          }
          if (!string.IsNullOrEmpty(selected))
          {
            FromDate = Convert.ToDateTime(selected);
            fromDate.SelectedDate = FromDate;
          }
        }
        if (toDate != null)
        {
          if (!string.IsNullOrEmpty(grid.MasterTableView.GetColumn("InspectionDate").CurrentFilterValue))
          {
            selected = grid.MasterTableView.GetColumn("InspectionDate").CurrentFilterValue;
            selected = selected.Split(' ')[1];
          }
          if (!string.IsNullOrEmpty(selected))
          {
            ToDate = Convert.ToDateTime(selected);
            toDate.SelectedDate = ToDate;
          }
        }
      }
    }
 
    protected void radInspection_OnItemDataBound(object sender, GridItemEventArgs e)
    {
      var grid = sender as RadGrid;
      if (grid == null)
      {
        return;
      }
      var filtering = e.Item as GridFilteringItem;
      if (filtering == null)
      {
        return;
      }
      var fromDate = filtering.FindControl("radFromInspectionDate") as RadDatePicker;
      var toDate = filtering.FindControl("radToInspectionDate") as RadDatePicker;
      var cmbDiv = filtering.FindControl("radDivisionFilter") as RadComboBox;
      if (fromDate != null)
      {
        fromDate.SelectedDate = FromDate;
      }
      if (toDate != null)
      {
        toDate.SelectedDate = ToDate;
      }
      if (cmbDiv != null)
      {
        cmbDiv.ClearSelection();
        cmbDiv.Items.Clear();
        var selected = "";
        if (!string.IsNullOrEmpty(grid.MasterTableView.GetColumn("Division").CurrentFilterValue))
        {
          selected = grid.MasterTableView.GetColumn("Division").CurrentFilterValue;
        }
        ListHelper.FillDivisionsForFilter(cmbDiv, ApplicationId, selected);
      }
    }
 
    protected void ibClearDate_OnClick(object sender, ImageClickEventArgs e)
    {
      radInspection.MasterTableView.FilterExpression = string.Empty;
      foreach (var column in radInspection.MasterTableView.RenderColumns)
      {
        var b = column as GridBoundColumn;
        if (b != null)
        {
          b.CurrentFilterValue = string.Empty;
        }
      }
      radInspection.Rebind();
    }
  }
}

How can I get the date filter preserved when other columns are filtered?

4 Answers, 1 is accepted

Sort by
0
Eyup
Telerik team
answered on 29 Jan 2016, 01:10 PM
Hi Mike,

Please use the built-in range filtering of the RadGrid. If you want to ignore the time, you can set the EnableTimeIndependentFiltering property to false. And if you want to handle the width, you can show the pickers on two rows:
http://www.telerik.com/forums/basic-filtering-datetime-range#J6au2nck4EKUQCxcC-8u9g

Hope this helps. If you insist on using a template, you can check the OrderDate from the second grid in this live sample:
http://demos.telerik.com/aspnet-ajax/grid/examples/functionality/filtering/filter-templates/defaultcs.aspx

Regards,
Eyup
Telerik
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 Feedback Portal and vote to affect the priority of the items
0
Mike
Top achievements
Rank 1
answered on 29 Jan 2016, 05:27 PM

Thanks for the update, seems to be working pretty good.  However, there is still another issue.  I generally like to highlight "today" on all my date pickers to give the user a better experience.  I am not able get that to work now for some reason.

Here is my column in my RadGrid

<telerik:GridDateTimeColumn DataField="inspection_datetime" HeaderText="Inspection Date" EnableTimeIndependentFiltering="False"
    PickerType="DatePicker" DataFormatString="{0:yyyy-MM-dd HH:mm tt}" UniqueName="InspectionDate" EnableRangeFiltering="True">
    <ItemStyle Width="7%" VerticalAlign="Top" HorizontalAlign="Left"></ItemStyle>
    <HeaderStyle Width="7%"></HeaderStyle>
</telerik:GridDateTimeColumn>
 

Here is my code-behind in the ItemDataBound Event:

 

var dtFilter = filtering["InspectionDate"];
if (dtFilter != null)
{
    var fromLabel = dtFilter.Controls[0] as LiteralControl;
    var fromDate = dtFilter.Controls[1] as RadDatePicker;
    var toLabel = dtFilter.Controls[3] as LiteralControl;
    var toDate = dtFilter.Controls[4] as RadDatePicker;
    if (fromLabel != null)
    {
        fromLabel.Text = string.Empty;
    }
    if (fromDate != null)
    {
        fromDate.DateInput.DisplayDateFormat = "yyyy-MM-dd";
        fromDate.DateInput.DateFormat = "yyyy-MM-dd";
        fromDate.DateInput.EmptyMessage = "From Date";
        var day = new RadCalendarDay {Repeatable = RecurringEvents.Today};
        day.ItemStyle.BackColor = Color.LightGray;
        day.ItemStyle.Font.Bold = true;
        day.ItemStyle.BorderStyle = BorderStyle.Solid;
        day.ItemStyle.BorderColor = Color.Black;
        day.ItemStyle.BorderWidth = new Unit(1);
        fromDate.Calendar.SpecialDays.Add(day);
    }
    if (toLabel != null)
    {
        toLabel.Text = "<br/>";
    }
    if (toDate != null)
    {
        toDate.DateInput.DisplayDateFormat = "yyyy-MM-dd";
        toDate.DateInput.DateFormat = "yyyy-MM-dd";
        toDate.DateInput.EmptyMessage = "To Date";
        var day = new RadCalendarDay {Repeatable = RecurringEvents.Today};
        day.ItemStyle.BackColor = Color.LightGray;
        day.ItemStyle.Font.Bold = true;
        day.ItemStyle.BorderStyle = BorderStyle.Solid;
        day.ItemStyle.BorderColor = Color.Black;
        day.ItemStyle.BorderWidth = new Unit(1);
        toDate.Calendar.SpecialDays.Add(day);
    }
}

 

How can I get "today" highlighted on the calendar controls?

0
Accepted
Eyup
Telerik team
answered on 03 Feb 2016, 08:42 AM
Hello Mike,

Your approach is correct. But the pickers in the grid use a SharedCalendar, so just replace the Calendar part:
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
    if (e.Item is GridFilteringItem)
    {
        GridFilteringItem item = (GridFilteringItem)e.Item;
        TableCell cell = item["OrderDate"];
        RadDatePicker fromPicker = cell.Controls[1] as RadDatePicker;
 
        RadCalendarDay day = new RadCalendarDay();
        day.Repeatable = Telerik.Web.UI.Calendar.RecurringEvents.Today;
        day.ItemStyle.CssClass = "rcToday";
        fromPicker.SharedCalendar.SpecialDays.Add(day);
    }
}

Looking forward to hearing from you.

Regards,
Eyup
Telerik
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 Feedback Portal and vote to affect the priority of the items
0
Mike
Top achievements
Rank 1
answered on 03 Feb 2016, 03:48 PM
Thanks!  I wasn't aware it was the SharedCalendar control instead of the Calendar control.
Tags
Grid
Asked by
Mike
Top achievements
Rank 1
Answers by
Eyup
Telerik team
Mike
Top achievements
Rank 1
Share this question
or