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

How to clear sorting?

11 Answers 447 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Maxim Tairov
Top achievements
Rank 1
Maxim Tairov asked on 16 Apr 2009, 10:24 AM

Hello Telerik!

I have some strange problem when I use internal sorting. My configuration: .NET 3.5 and latest version of Telerik.Web.UI assembly.

1. My Grid fully run-time created (columns, content). Property EnableViewState is false.

2. When I try to recreate grid I haven't any problem, util I don't use sorting.

Issue: If previous content had sorting on some column I can't recreate grid (columns, content).

Method RadGrid.Rebind() raise an Exception:

<Sorted_Column_Name> is neither a DataColumn nor a DataRelation for table Table1.

Stack Trace
at System.Data.DataRowView.get_Item(String property) at lambda_method(ExecutionScope , DataRowView ) at System.Linq.EnumerableSorter`2.ComputeKeys(TElement[] elements, Int32 count) at System.Linq.EnumerableSorter`1.Sort(TElement[] elements, Int32 count) at System.Linq.OrderedEnumerable`1.d__0.MoveNext() at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source) at lambda_method(ExecutionScope ) at System.Linq.EnumerableExecutor`1.Execute() at System.Linq.EnumerableExecutor`1.ExecuteBoxed() at System.Linq.EnumerableQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) at Telerik.Web.UI.GridDynamicQueryable.Count(IQueryable source) at Telerik.Web.UI.GridDataTableFromEnumerable.FillData35() at Telerik.Web.UI.GridDataTableFromEnumerable.FillData() at Telerik.Web.UI.GridResolveEnumerable.Initialize() at Telerik.Web.UI.GridResolveEnumerable.EnsureInitialized() at Telerik.Web.UI.GridResolveEnumerable.get_DataTable() at Telerik.Web.UI.GridEnumerableFromDataView..ctor(GridTableView owner, DataView dataView, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) at Telerik.Web.UI.GridDataSourceHelper.CreateGridEnumerable(GridTableView owner, IEnumerable enumerable, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) at Telerik.Web.UI.GridDataSourceHelper.GetResolvedDataSource(GridTableView owner, Object dataSource, String dataMember, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) at Telerik.Web.UI.GridTableView.get_ResolvedDataSource() at Telerik.Web.UI.GridTableView.CreateChildControls(IEnumerable dataSource, Boolean useDataSource) at System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) at System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) at System.Web.UI.WebControls.DataBoundControl.PerformSelect() at Telerik.Web.UI.GridTableView.PerformSelect() at System.Web.UI.WebControls.BaseDataBoundControl.DataBind() at Telerik.Web.UI.GridTableView.DataBind() at Telerik.Web.UI.RadGrid.DataBind() at Telerik.Web.UI.RadGrid.AutoDataBind(GridRebindReason rebindReason) at Telerik.Web.UI.RadGrid.Rebind() at DefContentPage.PopulateGrid()

Before Create new Columns and Binding I clear ALL previous settings and content:

RadGrid.MasterTableView.FilterExpression = String.Empty;  
RadGrid.MasterTableView.SortExpressions.Clear();
RadGrid.MasterTableView.GroupByExpressions.Clear();
RadGrid.MasterTableView.ClearSelectedItems();
RadGrid.MasterTableView.ClearEditItems();
RadGrid.AutoGenerateColumns = false;
RadGrid.MasterTableView.Columns.Clear();
RadGrid.MasterTableView.DataKeyNames = new string[0];
RadGrid.MasterTableView.DataSource = null;

//Create  new columns layout

RadGrid.Rebind(); 

For getting DataSource I am using NeedDataSource event. All time datasource is an instance of DataTable.

Please explain how can I recreate grid in case when my previous grid had sorting expression in some column.


11 Answers, 1 is accepted

Sort by
0
Maxim Tairov
Top achievements
Rank 1
answered on 16 Apr 2009, 12:56 PM

Some Details:

During Binding MasterTableView restore _sortExpression from ViewState. How It could be disabled?

0
Yavor
Telerik team
answered on 21 Apr 2009, 11:34 AM
Hi Maxim,

Clearing the RadGrid1.MasterTableView.SortExpressions collection, and rebinding the control will make sure no sort expressions are present.
I hope this suggestion helps.

Best wishes,
Yavor
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
0
Maxim Tairov
Top achievements
Rank 1
answered on 21 Apr 2009, 12:46 PM

Hello Yavor!

Not sure that It can help me. 

My application build grid at runtime. Imagine, there is a tree. All nodes contain specific configuration for grid (select query, column descriptions and so on). While I doesn't recreate grid after selecting new node everything works fine, but when I try to recreate grid after changing node in tree - I see error message that previous sorting column doesn't exist in grid. (Sure if I am not using internal sorting - grid will be recreaded without any errors)

I made some small investigation in this problem and find some strange behaviour:

BEFORE calling RadGrid.Rebind SortExpression is not actual!!! Because actual value comes during Binding method execute via calling MasterTableView.LoadControlState method. This is very strange, because usually ViewState properties are established BEHIND binding.

I guess that SortExpression.Clear() not work properlly all time.  Possible I can clear sort expression by manually creating new SortExpression for sorting column with no sort parameter. But in this case I should rebind (create) grid twice: 1. For clear sorting by using OLD content, and 2. For showing NEW content (with another columns). Is It possible to drop SortExpression withoutdouble Binding?

0
Yavor
Telerik team
answered on 24 Apr 2009, 08:37 AM
Hello Maxim,

Based on this information, it is hard to determine why the sorting expression is not properly reset.
If the issue persists, you can open a formal support ticket, and send us a small project, demonstrating your approach, for additional review and testing.

Regards,
Yavor
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
0
Maxim Tairov
Top achievements
Rank 1
answered on 30 Apr 2009, 08:04 AM
I have solved problem. Just override LoadControlState method in GridTableView.
0
Toby
Top achievements
Rank 1
answered on 23 Nov 2010, 05:15 PM
I am having the same issue, how exactly did you overcome it? Was it just due to the control loading the sorting information from the viewstate?

thanks
Toby
0
Radoslav
Telerik team
answered on 26 Nov 2010, 11:43 AM
Hello Toby,

Could you please try using the following code and let me know if the issue still exists:
JavaScript
var masterTable = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
masterTable.fireCommand("CustomCommand");

ASPX.CS
void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
   if (e.CommandName == "CustomCommand")
   {
       RadGrid1.MasterTableView.SortExpressions.Clear();
       RadGrid1.Rebind();
   }
}


Sincerely yours,
Radoslav
the Telerik team
Browse the vast support resources we have to jumpstart 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
manish
Top achievements
Rank 1
answered on 18 Jul 2011, 11:20 AM
Hi Maxim Tairov  Please provide me code using which you have solve this problem, I need it because the scenario which you provied  is as my requirements.
0
Maxim Tairov
Top achievements
Rank 1
answered on 18 Jul 2011, 12:26 PM
Hello All!
I see that problem still exist. It is very strange because I wrote  about this issue more than 2 years. As I rememember the reason of the issue is loading paramaters from ViewState during bunding method executing. This is bad approuch, because developer can't control loaded parameter before calling Binding.

Ok. Here is detailed description how we can control Control State behavour in Telerik Rad Grid. Not easy (unfortunattly).

1. Create child class from base Telerik RadGrid, and override CreateTableView method

 
public class MyBaseGrid : RadGrid
{
     public MyBaseGrid()
     {
     }
            
             // Overirde CreateTableView method for creating Custom MyGridTableView

       public override GridTableView CreateTableView()

       {

           MyGridTableView masterTableView = new MyGridTableView(this);

           masterTableView.Name = MASTER_TABLE_NAME;

           return masterTableView;

       }


       // Just for easy access to custom instance of MyGridTableView class
      public MyGridTableView MyTableView      
       {
         get { return (MyGridTableView) MasterTableView; }

 

       }

 

}

2. Create MyGridTableView class (as a child of GridTableView
public class MyGridTableView : GridTableView
  {
    protected bool _useControlState;
      
    public MyGridTableView(RadGrid grid) : base(grid)
    {
      _useControlState = true;
    }
  
    public bool UseControlState
    {
      get { return _useControlState;  }
      set { _useControlState = value; }
    }
  
    protected override void LoadControlState(object savedState)
    {
      if (UseControlState)
        base.LoadControlState(savedState);
    }
  }
3. By using property UseControlState you can enable or disable LoadControlState functions:
//Just example - my code contains more calling 
private
void PopulateGrid()
 {
   //disable control state
   contentGrid.MyTableView.UseControlState = false;
   contentGrid.MasterTableView.FilterExpression = String.Empty;
   contentGrid.MasterTableView.SortExpressions.Clear();
   contentGrid.MasterTableView.GroupByExpressions.Clear();
   contentGrid.MasterTableView.ClearSelectedItems();
   contentGrid.MasterTableView.ClearEditItems();      
   contentGrid.GlobalConfig = ConfigSettings; // Just Set NEW configurations to my MyBaseGrid instance
   contentGrid.Rebind();
   //enable control state again
   contentGrid.MyTableView.UseControlState = true;
}



0
Munish Sharma
Top achievements
Rank 1
answered on 28 Aug 2013, 04:07 AM
I am working on a radgrid which loads from datatable at runtime under NeedDataSource event. The grid is very dynamic and loads different columns in different cases. Everything works fine till I sort the column(either ascending or descending) and then do a postback to load new columns. When I do this it just fails to load the new changes.

Note: If I don't sort the column everything works fine. 

<telerik:RadAjaxManagerProxy ID="ampAnalysis" runat="server">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="rgAnalysis">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="rgAnalysis" LoadingPanelID="LoadingPanel"/>
                    </UpdatedControls>
                </telerik:AjaxSetting>                
            </AjaxSettings>
        </telerik:RadAjaxManagerProxy>
        
        <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server">
            <telerik:RadGrid ID="rgAnalysis" runat="server" ShowGroupPanel="false" Skin="Default" 
                AllowMultiRowSelection="True" AllowSorting="True" GridLines="None" BorderStyle="None" BorderWidth="0"   
                Height="500px" ShowFooter="True"  Width="100%" EnableViewState="False"
                AllowFilteringByColumn="True" PagerStyle-Mode="Slider" PageSize="12" AllowPaging="true" OnItemCommand="rgAnalysis_ItemCommand" >
                <GroupingSettings CaseSensitive="false" />
                <ExportSettings>
                    <Csv ColumnDelimiter="Tab" RowDelimiter="NewLine" FileExtension="txt" />
                    <Excel Format="Html" />
                    <Pdf FontType="Subset" PaperSize="Letter" AllowAdd="false" AllowCopy="false" AllowModify="false" AllowPrinting="true" Creator="ABI" 
                        PageBottomMargin="5mm" PageTopMargin="20mm" PageLeftMargin="5mm" PageRightMargin="5mm" PageHeight="297mm" PageWidth="420mm" />
                </ExportSettings>
                <FooterStyle HorizontalAlign="Right" Font-Bold="false"/>
                <MasterTableView AllowNaturalSort="true" ShowFooter="True" AllowMultiColumnSorting="true" EnableViewState="false" Width="100%">
                    <Columns>
                        <telerik:GridClientSelectColumn UniqueName="ClientSelectColumn" HeaderStyle-Width="50px" ItemStyle-Width="30px" />
                    </Columns>
                </MasterTableView>
                <ClientSettings>
                    <DataBinding EnableCaching="true"></DataBinding>
                    <Resizing ResizeGridOnColumnResize="true" />
                    <selecting AllowRowSelect="True" />
                    <Scrolling AllowScroll="True" SaveScrollPosition="true" FrozenColumnsCount="3">
                    </Scrolling>
                    <ClientEvents  OnRowSelected="rgAnalysis_RowSelected"  OnRowDeselected="rgAnalysis_RowDeselected" />
                </ClientSettings>
            </telerik:RadGrid>
        </telerik:RadAjaxPanel>


As I said the grid works perfectly fine in most all the cases except just this one. There is no other issue with the functionality. 

Say my report1 has column1, column2, column3 
and 
report2 has column4, column5, column6

When I run report1, it shows me the column1, column2 & column3 and when I run report2 it shows me column4, column5, column6

But the problem comes when I run report1 and sort any column(column1 or column2 or column3) and then try running report2. Here it goes to needdatasource event and get the data for report2 and then crashes somewhere without any exception. I tried debugging it and found that it only comes once in column created event when I do the sort and run the second report. When I don't do the sort and run the second report it comes multiple times to column created event.


I have attached Images when it works without sorting (Without Sort 1, Without Sort 2, Without Sort 3)
I have also attached Images when it doesn't work with sorting(With Sort 1,With Sort 2,With Sort 3, With Sort 4)

I have added GridClientSelectColumn to get checkboxes for every row in grid. And yes we can add columns dynamically with the GridClientSelectColumn from datatable in need datasource.

Moreover, telerik:RadAjaxPanel is enclosed around the grid to call javascript as:
RadAjaxPanel1.ResponseScripts.Add("PrintRadGrid('" + rgAnalysis.ClientID + "')")

Javascript:
function PrintRadGrid(radGridId) {
            var radGrid = $find(radGridId);

            if ($telerik.isIE) 
            {
                if (document.getElementById('ctl00_cphCenter_rgAnalysis_ctl00').style.tableLayout == 'fixed') 
                {
                    document.getElementById('ctl00_cphCenter_rgAnalysis_GridFooter').style.width = '100%';
                    document.getElementById('ctl00_cphCenter_rgAnalysis_GridHeader').style.width = '100%';
                    document.getElementById('ctl00_cphCenter_rgAnalysis_GridData').style.overflow = 'visible';
                }
                else 
                {
                    if (document.getElementById('ctl00_cphCenter_rgAnalysis_ctl00').style.tableLayout == 'auto') 
                    {
                        document.getElementById('ctl00_cphCenter_rgAnalysis_GridData').style.overflow = 'visible';
                    }
                }
            }

I am already using the sort clear command under postback before NeedDataSource but still the same problem./

command:
rgAnalysis.MasterTableView.SortExpressions.Clear()

0
Munish Sharma
Top achievements
Rank 1
answered on 30 Aug 2013, 04:33 AM
I have found the fix. I just needed to add another few lines of code on Form_Load event:

If Not Page.Request.Params.[Get]("__EVENTTARGET") Is Nothing Then
            If Page.Request.Params.[Get]("__EVENTTARGET").Contains("pnlReporting") Then
                rgAnalysis.MasterTableView.SortExpressions.Clear()
                rgAnalysis.DataBind()
            End If
        End If
Tags
Grid
Asked by
Maxim Tairov
Top achievements
Rank 1
Answers by
Maxim Tairov
Top achievements
Rank 1
Yavor
Telerik team
Toby
Top achievements
Rank 1
Radoslav
Telerik team
manish
Top achievements
Rank 1
Munish Sharma
Top achievements
Rank 1
Share this question
or