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

AutoPostBackOnFilter only for return and click

9 Answers 571 Views
Grid
This is a migrated thread and some comments may be shown as answers.
improwise
Top achievements
Rank 1
Iron
Iron
improwise asked on 04 May 2011, 05:19 PM
If you set the AutoPostBackOnFilter = true the filtering will start when you hit return, or click the filter button, but unfortunately, it will also start as soon as the filter goes out of focus (you move focus to something else) which prevents you from entering more than one search criteria before the filtering starts. How do you make it so that only return and click on filter image fires the filterning event?

Are we the only ones thinking that the "fire event when the filter textbox goes out of focus" is a strange default behaviour, or have we missed something here? I would say that pressing return or clicking on the filter image should be the default.

9 Answers, 1 is accepted

Sort by
0
Shinu
Top achievements
Rank 2
answered on 06 May 2011, 07:49 AM
Hello Patrik,

You can attach "onkeydown" to TextBox and give a try with the following code. Hope this helps you.

C#:
protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item is GridFilteringItem)
{
  GridFilteringItem filterItem = (GridFilteringItem)e.Item;
  TextBox txtbox = (TextBox)filterItem["UniqueName"].Controls[0];
  txtbox.Attributes.Add("onkeydown", "doFilter(this,event)");
}
}
  

Javascript:
<script type="text/javascript">
    function doFilter(sender, eventArgs)
     {
       if (eventArgs.keyCode == 13)
            {
            eventArgs.cancelBubble = true;
            eventArgs.returnValue = false;
              if (eventArgs.stopPropagation)
                   {
                eventArgs.stopPropagation();
                eventArgs.preventDefault();
                   }
            var masterTableView = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
            var uniqueName = "UniqueName"; // set Column UniqueName for the filtering TextBox
            masterTableView.filter(uniqueName, sender.value, Telerik.Web.UI.GridFilterFunction.Contains);
        }
    }
</script>

Thanks,
Shinu.
Lynn
Top achievements
Rank 2
commented on 03 Jun 2024, 10:41 AM

When I add the javascript code above to the webpage (after adding the code behind code lines), I receive the following error which prevents the display of the webpage:

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Is there any way to eliminate this error?

Thanks!

Lynn

Vasko
Telerik team
commented on 03 Jun 2024, 11:04 AM

Hello Lynn,

This is a common ASP.NET error, which occurs when there are code blocks in the control (as the error says) . The following StackOverflow thread delves into more details regarding it and ways to work around it.

Best regards,
Vasko
Progress Telerik

Lynn
Top achievements
Rank 2
commented on 03 Jun 2024, 11:27 AM

Vasko, 

I was able to get past this issue by searching for responses to the error message.  But once I got past it, neither the C# event code shown above in the original solution is ever executed and, thusly, the javascript code is also never executed.

Is the C# event (RadGri1_ItemCreated) the correct event to be trying to connect with?

 

Lynn

Vasko
Telerik team
commented on 04 Jun 2024, 05:27 AM

Hi Lynn,

I tried replicating the issue based on your comments but wasn't able to. 

I'd like to ask you to send an isolated sample project that replicates it, so I can take a closer look at what might be the root cause of this behavior. 

Kind regards,
Vasko
Progress Telerik

 
Lynn
Top achievements
Rank 2
commented on 06 Jun 2024, 12:35 AM

Vasko,

Thank you for your reply and I apologize for taking so much time to get back to you.  But I've been spending more time on my test project and I have successfully met all but one of my objectives.

Before continuing, I did try to attach a .zip file containing the smallest solution/project folder I could make in a reasonable time but received an error from your website saying it was too large (55MB after being zipped).  ASP.NET solution/project folders are always big.

Anyway, sorry I can't get the .zip file to you, but maybe you can answer my last question.

I have the filter capability working just fine with one exception.  I can key in the first 2 or 3 characters of a CONTAINS filter and the grid will respond accordingly without my having to press the ENTER key.  That's great and the results are always good and fast. 

Here's my issue though.  When I use such a filter mechanism for real, I will usually just key in the first few characters and wait for the first filtering response to come back.  Then I frequently may want to key another character or two to get the response rows down to a smaller count (depends on the data contents of course).  However, with your grid as soon as I can key in the first few characters and the filter applies to the grid, then the focus on the filter text box is lost.  If I want to key in another character or two, then I first have to click my mouse back into the desired filter input textbox and then I can key in the next character(s).

I have used the DataTables list/grid to a great extent in the past, but would prefer to use your grid tool.  However, I (and my commercial software users) can key in the second set of filter characters without first having to mouse click inside the filter textbox as DataTables gives this capability without any additional definition work.  I'm not complaining about your grid product, but really would like to be able to keep keying text characters for the second set of filter characters without having to move my hand to the mouse and click in the desired filter box.

Is there any way to accomplish this with your AJAX grid?  I have a perfect project example that demonstrates this, but can't get it to you tonight.  I can actually write some JavaScript that will set the focus on the correct filter textbox, but it only "flashes" for a second and then it's gone.  I would really like the filtering mechansim to return the focus to the filter textbox that it just left if possible.

I hope I've explained my question in a satisfactory manner!

Wishing you a great day when you get back in the office!

Thanks for your time and attention!

Lynn

Vasko
Telerik team
commented on 06 Jun 2024, 09:49 AM

Hi Lynn,

I understand the frustration with this behavior, therefore, I've created a sample solution that focuses on the filter text box after filtering is done: 

<telerik:RadGrid ID="RadGrid2" runat="server" AllowPaging="True" Width="800px" AllowFilteringByColumn="true"
    OnItemCreated="RadGrid2_ItemCreated" OnPreRender="RadGrid2_PreRender" OnItemCommand="RadGrid2_ItemCommand" OnNeedDataSource="RadGrid2_NeedDataSource">
    <MasterTableView AutoGenerateColumns="False"
        DataKeyNames="OrderID">
        <Columns>
            <telerik:GridBoundColumn DataField="OrderID" DataType="System.Int32"
                FilterControlAltText="Filter OrderID column" HeaderText="OrderID"
                ReadOnly="True" SortExpression="OrderID" UniqueName="OrderID">
            </telerik:GridBoundColumn>
            <telerik:GridDateTimeColumn DataField="OrderDate" DataType="System.DateTime"
                FilterControlAltText="Filter OrderDate column" HeaderText="OrderDate"
                SortExpression="OrderDate" UniqueName="OrderDate">
            </telerik:GridDateTimeColumn>
            <telerik:GridNumericColumn DataField="Freight" DataType="System.Decimal"
                FilterControlAltText="Filter Freight column" HeaderText="Freight"
                SortExpression="Freight" UniqueName="Freight">
            </telerik:GridNumericColumn>
            <telerik:GridBoundColumn DataField="ShipName"
                FilterControlAltText="Filter ShipName column" HeaderText="ShipName"
                SortExpression="ShipName" UniqueName="ShipName">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="ShipCountry"
                FilterControlAltText="Filter ShipCountry column" HeaderText="ShipCountry"
                SortExpression="ShipCountry" UniqueName="ShipCountry">
            </telerik:GridBoundColumn>
        </Columns>
    </MasterTableView>
</telerik:RadGrid>
string columnName;
protected void RadGrid2_PreRender(object sender, EventArgs e)
{
    GridFilteringItem filteringItem = (GridFilteringItem)RadGrid2.MasterTableView.GetItems(GridItemType.FilteringItem)[0];

    if (columnName != null)
    {
        TextBox box = filteringItem[columnName].Controls[0] as TextBox;
        box.Focus();
    }
}

protected void RadGrid2_ItemCommand(object sender, GridCommandEventArgs e)
{
    if (((Pair)(e.CommandArgument)).Second.ToString() == "OrderID")
    {
        columnName = "OrderID";
    }
    else if (((Pair)(e.CommandArgument)).Second.ToString() == "OrderDate")
    {
        columnName = "OrderDate";
    }
    else if (((Pair)(e.CommandArgument)).Second.ToString() == "Freight")
    {
        columnName = "Freight";
    }
    else if (((Pair)(e.CommandArgument)).Second.ToString() == "ShipName")
    {
        columnName = "ShipName";
    }
    else
    {
        columnName = "ShipCountry";
    }
}

protected void RadGrid2_ItemCreated(object sender, GridItemEventArgs e)
{
    if (e.Item is GridFilteringItem)
    {
        GridFilteringItem filterItem = (GridFilteringItem)e.Item;
        TextBox txtbox = (TextBox)filterItem["ShipName"].Controls[0];
        txtbox.Attributes.Add("onkeydown", "doFilter(this,event)");
    }
}

protected void RadGrid2_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
    (sender as RadGrid).DataSource = OrdersTable();
}

private DataTable OrdersTable()
{
    DataTable dt = new DataTable();

    dt.Columns.Add(new DataColumn("OrderID", typeof(int)));
    dt.Columns.Add(new DataColumn("OrderDate", typeof(DateTime)));
    dt.Columns.Add(new DataColumn("Freight", typeof(double)));
    dt.Columns.Add(new DataColumn("ShipName", typeof(string)));
    dt.Columns.Add(new DataColumn("ShipCountry", typeof(string)));

    dt.PrimaryKey = new DataColumn[] { dt.Columns["OrderID"] };

    for (int i = 0; i < 100; i++)
    {
        int index = i + 1;

        DataRow row = dt.NewRow();

        row["OrderID"] = index;
        row["OrderDate"] = DateTime.Now.Date.AddDays(index);
        row["Freight"] = index * 0.01;
        row["ShipName"] = "Name " + index;
        row["ShipCountry"] = "Country " + index;

        dt.Rows.Add(row);
    }

    return dt;
}
function doFilter(sender, eventArgs) {
    var grid = $find("<%= RadGrid2.ClientID %>");
    var masterTableView = grid.get_masterTableView();
    var uniqueName = "ShipName"; // set Column UniqueName for the filtering TextBox

    if (eventArgs.key == "Enter") {
        masterTableView.filter(uniqueName, sender.value, Telerik.Web.UI.GridFilterFunction.Contains);
    }
}

You can copy-paste it and see if the suggestion will be of use to your scenario.

Kind regards,
Vasko
Progress Telerik

0
improwise
Top achievements
Rank 1
Iron
Iron
answered on 08 May 2011, 08:25 PM
Thanks for the suggestion.

But is it only me thinking that:

1. There really should be a property for this, not something you should  have to write code for
2. The default behaviour should be return key or clicking the filter symbol, and that "out of focus event" is strange and should not be default.

 
0
Tsvetina
Telerik team
answered on 12 May 2011, 07:13 AM
Hello Patrik,

This behavior is what many customers request to have - to filter
once the filter textbox loses focus. Modifying this behavior would be a breaking change for their sites.
Additionally, since the property is set for each column separately, it makes sense that its filter will postback before you can set criteria in other column filters.

Anyway, if you are not happy with this behavior, one option is to implement filtering for your grid using RadFilter, where you can set criteria for all columns before actually filtering as demonstrated here:
Filtering with RadFilter

In case this still does not satisy your requirements, you could submit a feature request. If other customers demand such kind of built-in property for RadGrid, too, it will be implemented separately from AutoPostBackOnFilter.

All the best,
Tsvetina
the Telerik team

Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

0
improwise
Top achievements
Rank 1
Iron
Iron
answered on 12 May 2011, 09:09 AM
Acutally, to some extent, I agree with you. Based on the name of the property AutoPostBackOnFilter, it really should be used for automatic operations, and neither hitting return och clicking a button is an automatic operation as I see it. But as far as I know, this is the only way you can make searching with return/filter icon click (default search with includes that is), or is there a better way?

What is the best way to implement a search button in the RadGrid?
0
Tsvetina
Telerik team
answered on 17 May 2011, 03:58 PM
Hi Patrik,

Both actions that you mentioned would cause the filter textbox to lose focus and cause an auto postback, so they are expected to be a part of the AutoPostBackOnFilter functionality.

In my opinion, a clean way to perform filtering on multiple columns on a single button click is the approach I linked to in my previous post - the RadGrid integration with RadFilter demo.

Kind regards,
Tsvetina
the Telerik team

Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

0
improwise
Top achievements
Rank 1
Iron
Iron
answered on 18 May 2011, 01:24 PM
I have to be honest and say that the RadFilter is perhaps the most confusing component in the Telerik-pack, and not even I as a senior software developer find that I know how to use it, without search and trial, at least not in the implementation you linked to. I can guarantee that very few of the users of our system would understand it either. If there is an alternative implementation of the RadFilter, please provide an URL so we can see it in action.
0
Tsvetina
Telerik team
answered on 24 May 2011, 08:47 AM
Hi Patrik,

In case you do not want to use RadFilter, you would need to prevent the grid from firing its built-in filtering command on choosing an option from the filter menu. Then, on a single button click, manually build the filter expression by looping through the grid columns, assign it to the GridInstance.MasterTableView.FilterExpression and rebind the grid. This is generally what RadFilter would do automatically for the grid if used.

Best wishes,
Tsvetina
the Telerik team

Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

0
Karl
Top achievements
Rank 1
answered on 22 Aug 2011, 12:47 PM
I want to apply this to my grid filtering so the filter gets applied on the "Return" key press, but don't know what value to use instead of "UniqueName"?
Do i need to setup each column in the codebehind and bind the javascript to each one?

In the javascript, how do I know which field im actually filtering on?

I need to have 4 filtered columns, but the javascript looks like the field name must be set to "uniqueName". Obviously they cant all be called ""uniqueName" as it wouldn't be very unique, and it doesn't look like I can pass through the column name?
 
Do you have any working examples of this code, particularly for filtering multiple columns?
0
Tsvetina
Telerik team
answered on 23 Aug 2011, 11:45 AM
Hi Karl,

Is it that you do not want to filter on loss of focus? Because if this is acceptable for you, you could directly use the grid built-in autopostback filtering, as in this demo:
Basic Filtering

If you want to only use the Enter key press for filtering, you would need to attach the client event for each filter textbox. Then, in the client function use the getColumnUniqueNameByCellIndex method to access the column unique name. As for the cell needed by this method, it will be the parentNode of the textbox element.
function doFilter(sender, eventArgs) {
    if (eventArgs.keyCode == 13) {
        eventArgs.cancelBubble = true;
        eventArgs.returnValue = false;
        if (eventArgs.stopPropagation) {
            eventArgs.stopPropagation();
            eventArgs.preventDefault();
        }
        var masterTableView = $find("<%= dbgSelectedCourseCodes.ClientID %>").get_masterTableView();
        var tableElement = masterTableView.get_element();
        var header = $telerik.$(tableElement).find('th.rgHeader')[0].parentNode;
        var uniqueName = masterTableView.getColumnUniqueNameByCellIndex(header, sender.parentNode.cellIndex);
        masterTableView.filter(uniqueName, sender.value, Telerik.Web.UI.GridFilterFunction.Contains);
    }
}



Best wishes,
Tsvetina
the Telerik team

Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>

Tags
Grid
Asked by
improwise
Top achievements
Rank 1
Iron
Iron
Answers by
Shinu
Top achievements
Rank 2
improwise
Top achievements
Rank 1
Iron
Iron
Tsvetina
Telerik team
Karl
Top achievements
Rank 1
Share this question
or