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

Applying a Default Filter Condition

10 Answers 915 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Mike
Top achievements
Rank 1
Mike asked on 20 Dec 2013, 12:23 AM
I have a grid that has a GridDateTimeColumn, and I'm trying to apply a default filter on page load.  I do have the AllowFiltering property set to true on the column, as well as the grid itself and I've also set the current filter condition [this part works].  I have a data source that is loaded with a large date range, but the users are requesting to hide most of the data so it's available for searching.  I've tried following this example: http://www.telerik.com/community/forums/aspnet-ajax/grid/default-filter-on-initial-load-for-griddatetimecolumn-with-rangefiltering.aspx but it didn't apply the filter - it just fills the date in the filter box.

I should also note, that I am trying to apply the filter in my code-behind.
private void LoadInfo(bool forceBind = true)
{
    radJobPostings.DataSource = JobPosting.LoadVAllJobPostings(user_id, _defaultFromDate);  //_defaultFromDate = Today - 3 years
    if (forceBind)
    {
        radJobPostings.MasterTableView.GetColumn("PostedDate").CurrentFilterValue = DateTime.Today.AddDays(-180).ToShortDateString();
        radJobPostings.DataBind();
    }
}

10 Answers, 1 is accepted

Sort by
0
Princy
Top achievements
Rank 2
answered on 20 Dec 2013, 04:17 AM
Hi Mike,

You can use the grid's PreRender event to specify an initial filter. Note that after setting the filter, you must rebind the grid. Please try the following code snippet.

C#:
protected void RadGrid1_PreRender(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        RadGrid1.MasterTableView.FilterExpression = string.Format("([PostedDate] = '{0}')", DateTime.Today.AddDays(-180).ToShortDateString());
        GridColumn column = RadGrid1.MasterTableView.GetColumnSafe("PostedDate");
        column.CurrentFilterFunction = GridKnownFunction.EqualTo;
        column.CurrentFilterValue = DateTime.Today.AddDays(-180).ToShortDateString();
        RadGrid1.MasterTableView.Rebind();
    }
}

Thanks,
Princy
0
Mike
Top achievements
Rank 1
answered on 20 Dec 2013, 04:25 PM
Thanks for the reply.  Unfortunately I'm now getting an exception thrown on the Rebind line.  The exception is "ParseException was unhandled by user code" with "Additional information: Expression expected".  From what I can tell, I have all the expressions set and I'm at a loss.  Any ideas?
0
Princy
Top achievements
Rank 2
answered on 21 Dec 2013, 03:56 AM
Hi Mike,

Please set EnableLinqExpressions="false".

ASPX:
<telerik:RadGrid ID="RadGrid1" runat="server" EnableLinqExpressions="false". . .>

Thanks,
Princy
0
Mike
Top achievements
Rank 1
answered on 23 Dec 2013, 04:01 PM
Thanks, it now compiles and runs -  however it is still not applying the filter condition, it just fills the filter text box.  To apply the filter, I still have to select the filter condition beside the filter text box.
0
Princy
Top achievements
Rank 2
answered on 24 Dec 2013, 05:06 AM
Hi Mike,

Can you try the filter Expression as follows, If this doesn't help, please provide your full code snippet.

C#:
RadGrid1.MasterTableView.FilterExpression = string.Format("(PostedDate = '{0}')", DateTime.Today.AddDays(-180).ToShortDateString());

Thanks,
Princy
0
Mike
Top achievements
Rank 1
answered on 24 Dec 2013, 03:46 PM

Unfortunately, it did not work.
Page:

<telerik:RadGrid ID="radJobPostings" runat="server" AllowPaging="true" OnNeedDataSource="radJobPostings_NeedDataSource" AllowSorting="true" ShowHeader="true" CellSpacing="0" GridLines="None"
                Width="100%" CssClass="table_data" BorderStyle="None" OnItemCommand="radJobPosting_ItemCommand" AllowFilteringByColumn="true" PageSize="20" AllowMultiRowSelection="False"
                OnPreRender="radJobPostings_OnPreRender" EnableLinqExpressions="False">
                <MasterTableView CommandItemDisplay="Top" AutoGenerateColumns="false" DataKeyNames="jobposting_id" TableLayout="Auto" GridLines="None" AllowFilteringByColumn="true"
                    NoMasterRecordsText="No Job Posting records">
                    <CommandItemTemplate>
                        <div class="control_heading">
                            <div style="float:left">Job Postings</div>
                            <div style="float:right;padding-right:10px;">
                                <a class="nlinks" href="#" onclick="javascript:OpenModalWindow('EditJobPosting.aspx',730,500);" style="color:#fff">
                                    <img src="icons/page_add.png" style="border:none;" alt="New Job Posting" />New</a>
                            </div>
                        </div>
                    </CommandItemTemplate>
                    <Columns>
                        <telerik:GridBoundColumn DataField="jobposting_id" HeaderText="JPID" AllowFiltering="False" AllowSorting="False" Visible="False"></telerik:GridBoundColumn>
                        <telerik:GridButtonColumn CommandName="AssignEmployees" ButtonType="ImageButton" UniqueName="AssignEmployees" Text="Assign" ImageUrl="icons/user_add.png"
                            HeaderStyle-Width="1%"></telerik:GridButtonColumn>
                        <telerik:GridButtonColumn CommandName="Select" ButtonType="ImageButton" UniqueName="Select" Text="Select" ImageUrl="icons/magnifier.png"
                            HeaderStyle-Width="1%"></telerik:GridButtonColumn>
                        <telerik:GridTemplateColumn AllowFiltering="false">
                            <ItemTemplate>
                                <a href="javascript:OpenModalWindow('EditJobPosting.aspx?id=<%# Eval("jobposting_id") %>',730,500)">
                                    <img src="icons/page_edit.png" style="border: 0" alt="Edit" /></a>
                            </ItemTemplate>
                        </telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn AllowFiltering="false">
                            <ItemTemplate>
                                <a href='PrintForm.aspx?id=<%# Eval("jobposting_id") %>' target="_blank">
                                    <img src="icons/printer.png" alt="Print" style="border: 0" /></a>
                            </ItemTemplate>
                        </telerik:GridTemplateColumn>
                        <telerik:GridBoundColumn DataField="division_description" HeaderText="Division" AllowFiltering="true" AllowSorting="true" HeaderStyle-Font-Bold="true"
                            AutoPostBackOnFilter="True" FilterControlWidth="60px" />
                        <telerik:GridBoundColumn DataField="posting_no" HeaderText="Posting #" HeaderStyle-Width="12%" AllowFiltering="True" AllowSorting="true" HeaderStyle-Font-Bold="true"
                            AutoPostBackOnFilter="True" FilterControlWidth="50px" />
                        <telerik:GridBoundColumn DataField="job_description" HeaderText="Job Name" ItemStyle-Wrap="true" AllowFiltering="true" AllowSorting="true" HeaderStyle-Font-Bold="true"
                            AutoPostBackOnFilter="True" FilterControlWidth="85px" />
                        <telerik:GridBoundColumn DataField="mill_area_description" HeaderText="Mill Area" AllowFiltering="true" AllowSorting="true" HeaderStyle-Font-Bold="true"
                            AutoPostBackOnFilter="True" FilterControlWidth="65px" />
                        <telerik:GridDateTimeColumn DataField="posted_date" HeaderText="Posted Date" UniqueName="PostedDate" DataFormatString="{0:MMM dd, yyyy}" AllowFiltering="true" AllowSorting="true"
                            CurrentFilterFunction="GreaterThanOrEqualTo" HeaderStyle-Font-Bold="true" PickerType="DatePicker" FilterControlWidth="95px" EnableRangeFiltering="False" EnableTimeIndependentFiltering="False">
                            <ItemStyle Width="95px"></ItemStyle>
                            <HeaderStyle Width="100px"></HeaderStyle>
                        </telerik:GridDateTimeColumn>
                        <telerik:GridDateTimeColumn DataField="closing_date" HeaderText="Closing Date" DataFormatString="{0:MMM dd, yyyy}" ItemStyle-Wrap="false" AllowFiltering="false"
                            AllowSorting="true" HeaderStyle-Font-Bold="true"/>
                    </Columns>
                </MasterTableView>
            </telerik:RadGrid>


Code Behind:

public partial class JobPostings : PageBase
    {
        private readonly DateTime _defaultFromDate = DateTime.Today.AddYears(-3); //DateTime.Now.AddDays( -180 );
 
        private int SelectedItem
        {
            get { return ViewState["SelectedItem"] != null ? Convert.ToInt32(ViewState["SelectedItem"].ToString()) : -1; }
            set { ViewState["SelectedItem"] = value; }
        }
 
        //----------------------------------------------------------------------------------------
 
        protected void Page_Load(object sender, EventArgs e)
        {
            ReloadDataEvent += JobPostings_ReloadDataEvent;
            if (!IsPostBack)
            {
                LoadInfo();
            }
        }
 
        //----------------------------------------------------------------------------------------
 
        private void LoadInfo(bool forceBind = true)
        {
            radJobPostings.DataSource = JobPosting.LoadVAllJobPostings(SSN, _defaultFromDate);
            if (forceBind)
            {
                radJobPostings.DataBind();  //tried with this line as is and commented out
            }
        }
 
        //----------------------------------------------------------------------------------------
 
        protected void AssignEmployees_Click(object sender, EventArgs e)
        {
            pnlAssignEmployees.Visible = true;
            string[] employees = ucEmployees.GetEmployees();
 
            #region Check to ensure there are enough people chosen already
 
            var j = JobPosting.LoadVJobPosting(SelectedItem);
            if (ucEmployees.MaximumEmployees != -1 && (j != null && j.no_required != employees.Length))
            {
                lblMessage.Text = "There are not enough employees selected for the posting";
                lblMessage.ForeColor = System.Drawing.Color.Red;
                return;
            }
 
            #endregion
 
            int jobPostingId = SelectedItem;//(int)radJobPostings.SelectedValue;
 
            using (TransactionScope ts = new TransactionScope())
            {
                var jobPosting = JobPosting.LoadJobPosting(jobPostingId);
 
                var postings = JobPosting.LoadPostingsFromJobPosting(jobPostingId);
 
                foreach (var post in postings)
                {
                    if (string.Equals(post.declined, "0"))
                    {
                        JobPosting.RemovePosting(post);
                        Competency.RemoveCompetencyFromPosting(post.ssn, post.job_id);
                    }
                }
 
                foreach (string emp in employees)
                {
                    // Expire the current posting for the employee (update the posting's End Date)
                    var existingPostings = JobPosting.LoadPostingsWithoutEndDate(jobPosting, emp);
 
                    if (existingPostings.Count == 1)
                    {
                        existingPostings[0].end_date = DateTime.Now;
                        existingPostings[0].modify_by = DisplayName;
                        existingPostings[0].modify_date = DateTime.Now;
                    }
 
                    // Add the new posting for the employee (with no End date)
                    Posting posting = new Posting
                      {
                          ssn = emp,
                          job_id = jobPosting.job_id,
                          jobposting_id = jobPostingId,
                          start_date = DateTime.Now,
                          end_date = null,
                          declined = "0",
                          create_date = DateTime.Now,
                          create_by = DisplayName,
                          modify_date = DateTime.Now,
                          modify_by = DisplayName
                      };
                    JobPosting.SavePosting(posting);
 
                    // Add a competency record for the employee to reflect they're competent for the job they were just assigned
                    DAL.Competency cmp = new DAL.Competency
                      {
                          ssn = emp,
                          module_id = (int)EDMS.Classes.Modules.Competencies,
                          job_id = jobPosting.job_id,
                          start_date = posting.start_date,
                          create_date = DateTime.Now,
                          modify_date = DateTime.Now,
                          create_by = DisplayName,
                          modify_by = DisplayName,
                          inactive = false,
                      };
                    Competency.SaveCompetency(cmp);
                }
 
                jobPosting.closed = true;
                JobPosting.SaveJobPosting(jobPosting);
 
                ts.Complete();
            }
 
            LoadInfo();
            pnlAssignEmployees.Visible = false;
            pnlAssignedTo.Visible = false;
        }
 
        //----------------------------------------------------------------------------------------
 
        protected void Cancel_Click(object sender, EventArgs e)
        {
            pnlAssignEmployees.Visible = false;
            pnlAssignedTo.Visible = false;
        }
 
        //----------------------------------------------------------------------------------------
 
        private void ShowAssignEmployees()
        {
            int jobPostingId = SelectedItem;
 
            var posting = JobPosting.LoadVJobPosting(jobPostingId);
 
            int noToBeAssigned = posting.assigned.HasValue ? posting.no_required - (int)posting.assigned : posting.no_required;
 
            ShowAssignedEmployees(jobPostingId);
            if (IsUserLimited)
            {
                if (posting.closed != 1)
                {
                    ucEmployees.LoadInfo(noToBeAssigned, posting.no_required, posting.division, jobPostingId);
                    pnlAssignEmployees.Visible = true;
                }
                else
                {
                    lblMessage.Text = "The posting has already been closed.";
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                }
            }
            else
            {
                ucEmployees.LoadInfo(noToBeAssigned, posting.no_required, posting.division, jobPostingId);
                pnlAssignEmployees.Visible = true;
                if (posting.closed != 1)
                {
                    lblMessage.Text = "The posting has already been closed.";
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
 
        //----------------------------------------------------------------------------------------
 
        private void ShowJobPosting()
        {
            int jobPostingId = SelectedItem;
            //pnlAssignEmployees.Visible = false;
            ShowAssignedEmployees(jobPostingId);
 
            ucViewJobPosting.LoadInfo(jobPostingId);
            pnlViewPosting.Visible = true;
        }
 
        //----------------------------------------------------------------------------------------
 
        private void ShowAssignedEmployees(int jpId)
        {
            var list = JobPosting.LoadVAssignedPostings(jpId);
            radAssignedTo.DataSource = list;
            radAssignedTo.DataBind();
            pnlAssignedTo.Visible = true;
        }
 
        //----------------------------------------------------------------------------------------
 
        private void JobPostings_ReloadDataEvent(object sender, EventArgs e)
        {
            LoadInfo();
            ucEmployees.RefreshAllData();
            ucViewJobPosting.RefreshAllData();
        }
 
        //----------------------------------------------------------------------------------------
 
        protected void radJobPostings_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            LoadInfo(false);
        }
 
        //----------------------------------------------------------------------------------------
 
        protected void radJobPosting_ItemCommand(object sender, GridCommandEventArgs e)
        {
            GridDataItem item = e.Item as GridDataItem;
            if (item != null)
            {
                e.Item.Selected = true;
                SelectedItem = Convert.ToInt32(item.GetDataKeyValue("jobposting_id").ToString());
            }
            switch (e.CommandName)
            {
                case "AssignEmployees":
                    pnlAssignEmployees.Visible = true;
                    pnlViewPosting.Visible = false;
                    pnlAssignedTo.Visible = true;
                    ShowAssignEmployees();
                    break;
                case "Select":
                    pnlViewPosting.Visible = true;
                    pnlAssignEmployees.Visible = false;
                    ShowJobPosting();
                    break;
            }
        }
 
        //----------------------------------------------------------------------------------------
 
        protected void radAssignedTo_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            ShowAssignEmployees();
        }
 
        //----------------------------------------------------------------------------------------
 
        protected override void RefreshAllData()
        {
            base.RefreshAllData();
            ucEmployees.RefreshAllData();
            ucViewJobPosting.RefreshAllData();
        }
 
        protected void radJobPostings_OnPreRender(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                var date = DateTime.Today.AddDays(-180).ToShortDateString();
                radJobPostings.MasterTableView.FilterExpression = string.Format("(PostedDate = '{0}')", date);
                GridColumn column = radJobPostings.MasterTableView.GetColumn("PostedDate");
                column.CurrentFilterFunction = GridKnownFunction.EqualTo;
                column.CurrentFilterValue = date;
                radJobPostings.MasterTableView.Rebind();
            }
        }
    }


Thanks!  Happy Holidays!

0
Eyup
Telerik team
answered on 25 Dec 2013, 05:45 PM
Hello Mike,

Please note that using DataBind() is not recommended. Performing complex grid operations such as Inserting, Deleting, Updating, Hierarchy relations, Grouping, Paging, Sorting, Filtering, etc. require accommodating appropriate database operations.  Therefore, we suggest you to avoid Simple Databinding and strongly recommend the use of more advanced databinding methods, which automatically handle the aforementioned functions:
Declarative DataSource
Advanced Data Binding

Make the suggested modification and the approach demonstrated in the mentioned article should work as expected:
http://www.telerik.com/help/aspnet-ajax/grid-applying-default-filter-on-initial-load.html

I hope this will prove helpful. Please let us know about the result.

Regards,
Eyup
Telerik
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to the blog feed now.
0
Mike
Top achievements
Rank 1
answered on 03 Jan 2014, 03:42 PM
I've adjusted my code to remove the explicit data binding, and it still doesn't filter on initial load.  just the filter text box is filled in with a value.
0
Accepted
Konstantin Dikov
Telerik team
answered on 08 Jan 2014, 09:47 AM
Hello Mike,

For your convenience I have prepared a sample page with your GridDateTimeColumn settings. Please refer to the attached files and see what differs in your project.

Hope that helps.


Regards,
Konstantin Dikov
Telerik
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to the blog feed now.
0
Mike
Top achievements
Rank 1
answered on 08 Jan 2014, 05:10 PM
Well, I know where my error was now.

On the line:
radJobPostings.MasterTableView.FilterExpression = string.Format("([posted_date] >= '{0}')", date);

I had [PostedDate] instead of the actual column name in the data source.

Seems to have solved my issue, thanks!

Tags
Grid
Asked by
Mike
Top achievements
Rank 1
Answers by
Princy
Top achievements
Rank 2
Mike
Top achievements
Rank 1
Eyup
Telerik team
Konstantin Dikov
Telerik team
Share this question
or