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

Paging with Radgrid

9 Answers 473 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Rob Venable
Top achievements
Rank 1
Rob Venable asked on 18 Jan 2011, 03:54 AM

Can anyone help me with Paging and Radgrid? I've tried looking at the tutorials on the Telerik site but they don't have any real world examples.
I've got my own objects and I don't use an ObjectDataSource...I'm trying to get it to work with my own code. This is what I'm trying to do. On page load, I get my list of Products and set it in Viewstate and then I bind it to my Grid. I then use the RadGrid_PageIndexChanged even to go through my Product List from ViewState and find the next set of products within my collection and re-bind my grid.
Would this work? Here's what I got:

<telerik:RadGrid ID="gridProducts" runat="server" AllowPaging="True" 
        AutoGenerateColumns="False" GridLines="None" 
        Skin="Outlook" width="675px" ShowFooter="True">
  <HeaderContextMenu EnableImageSprites="True" CssClass="GridContextMenu GridContextMenu_Outlook"></HeaderContextMenu>
  
        <PagerStyle AlwaysVisible="True" />
  
        <MasterTableView allowcustompaging="True" PageSize="5">
        <CommandItemSettings ExportToPdfText="Export to Pdf"></CommandItemSettings>
  
        <RowIndicatorColumn>
        <HeaderStyle Width="20px"></HeaderStyle>
        </RowIndicatorColumn>
  
        <ExpandCollapseColumn>
        <HeaderStyle Width="20px"></HeaderStyle>
        </ExpandCollapseColumn>
          <Columns>
               
            <telerik:GridTemplateColumn HeaderText="Item" UniqueName="Item">
              <ItemTemplate >
                  <telerik:RadBinaryImage ID="rbiItem" runat="server" /><br />
                  <asp:LinkButton ID="lnkView" runat="server">View Details</asp:LinkButton>  
              </ItemTemplate>
              <ItemStyle VerticalAlign="Top" HorizontalAlign="Center" Width="125px" />
            </telerik:GridTemplateColumn>
            <telerik:GridTemplateColumn HeaderText="Item Description" UniqueName="ItemDescription">
              <ItemTemplate>
                <asp:Label ID="lblItem" CssClass="ItemName" runat="server" Text=""></asp:Label>
                <br />
                <asp:Label ID="lblDescription" runat="server" Text=""></asp:Label>
              </ItemTemplate>
              <ItemStyle VerticalAlign="Top" />
            </telerik:GridTemplateColumn>
            <telerik:GridTemplateColumn HeaderText="Price" UniqueName="Price">
              <ItemTemplate>
                <asp:Label ID="lblPrice" runat="server" Text=""></asp:Label>
              </ItemTemplate>
              <HeaderStyle HorizontalAlign="Center" />
              <ItemStyle HorizontalAlign="Right" Width="50px" />
            </telerik:GridTemplateColumn>
            <telerik:GridTemplateColumn HeaderText="Buy Now">
              <ItemTemplate>
                <asp:ImageButton ID="imgCart" OnCommand="imgCart_Command" CommandName="Add" runat="server" />
              </ItemTemplate>
              <HeaderStyle HorizontalAlign="Center" />
              <ItemStyle HorizontalAlign="Center" Width="100px" />
            </telerik:GridTemplateColumn>
          </Columns>
  
<EditFormSettings>
<EditColumn FilterControlAltText="Filter EditCommandColumn column"></EditColumn>
</EditFormSettings>
          <PagerStyle AlwaysVisible="True" />
        </MasterTableView>
        <ClientSettings>
          <Selecting AllowRowSelect="True" />
        </ClientSettings>
  
<FilterMenu EnableImageSprites="False"></FilterMenu>
      </telerik:RadGrid>

...and here's the code behind:

Partial Public Class Products
    Inherits BasePage
  
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            InitializeControls()
        End If
    End Sub
  
    Private Sub InitializeControls()
        '== Labels
        lblTitle.Text = "Products"
        btnSearch.Text = "Search"
        imgBtnSearch.ImageUrl = "~/images/go.bmp"
        imgBtnSearch.Width = Unit.Pixel(30)
        imgBtnSearch.Height = Unit.Pixel(30)
  
        lblNoRecords.Visible = False
  
        lblNoRecords.Text = "There are no items to display."
  
          
        radCategories.DataTextField = "CategoryName"
        radCategories.DataValueField = "CategoryID"
        radCategories.DataSource = CategoryBL.GetAllCategories()
        radCategories.DataBind()
        radCategories.Items.Insert(0, New RadComboBoxItem("select a category", ""))
        radCategories.Items.Insert(1, New RadComboBoxItem("View All", "-1"))
  
        LoadGrid()
    End Sub
  
  
  
    Private Sub LoadGrid()
       'Set the products in ViewState
        Me.Products = ProductBL.GetActiveProducts
        gridProducts.DataSource = Me.Products
        gridProducts.DataBind()
  
    End Sub
  
 Private Sub gridProducts_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles gridProducts.ItemDataBound
        If (TypeOf (e.Item) Is GridDataItem) Then
            Dim dr As PawnShop.Entities.Product = CType(e.Item.DataItem, PawnShop.Entities.Product)
  
            Dim lnkView As LinkButton = CType(e.Item.FindControl("lnkView"), LinkButton)
            lnkView.PostBackUrl = "Details.aspx?id=" & HttpUtility.HtmlEncode(dr.ProductID.ToString)
  
            Dim lblItem As Label = CType(e.Item.FindControl("lblItem"), Label)
            lblItem.Text = HttpUtility.HtmlEncode(dr.Name)
  
            Dim lblDescription As Label = CType(e.Item.FindControl("lblDescription"), Label)
            lblDescription.Text = HttpUtility.HtmlEncode(dr.Description)
  
            Dim lblPrice As Label = CType(e.Item.FindControl("lblPrice"), Label)
            lblPrice.Text = String.Format(Constants.CURRENCY, dr.Price)
  
            Dim imgCart As ImageButton = CType(e.Item.FindControl("imgCart"), ImageButton)
            'imgCart.ImageUrl = "~/images/shoping_cart_sm.png"
            imgCart.ImageUrl = "~/images/buy_now.gif"
            imgCart.CommandArgument = dr.ProductID.ToString
            imgCart.CommandName = "Add"
  
            Dim rbiItem As RadBinaryImage = CType(e.Item.FindControl("rbiItem"), RadBinaryImage)
            rbiItem.DataValue = dr.imgContent
            rbiItem.Width = 100
            'rbiItem.Height = 100
            rbiItem.ResizeMode = BinaryImageResizeMode.Fit
            rbiItem.AutoAdjustImageControlSize = False
            rbiItem.AlternateText = HttpUtility.HtmlEncode(dr.Name)
  
            'Dim imgProduct As Image = CType(e.Item.FindControl("imgProduct"), Image)
            'imgProduct.ImageUrl = "~/Handler.ashx?id=" & dr.ProductID
  
        End If
          
    End Sub
  
   
    Private Sub gridProducts_PageIndexChanged(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridPageChangedEventArgs) Handles gridProducts.PageIndexChanged
        Dim startRowIndex As Integer = gridProducts.CurrentPageIndex * gridProducts.PageSize
        Dim maximumRows As Integer = gridProducts.PageSize
  
        Dim myList As New List(Of Product)
        For i As Integer = 0 To Me.Products.Count
            If i >= gridProducts.CurrentPageIndex AndAlso i <= gridProducts.PageSize Then
                myList.Add(Me.Products(i))
            End If
        Next
        If myList.Count > 0 Then
            gridProducts.DataSource = myList
        End If
    End Sub
  
      
    Private Sub gridProducts_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gridProducts.SelectedIndexChanged
        Dim startRowIndex As Integer = gridProducts.CurrentPageIndex * gridProducts.PageSize
        Dim maximumRows As Integer = gridProducts.PageSize
  
        Dim myList As New List(Of Product)
        For i As Integer = 0 To Me.Products.Count
            If i >= gridProducts.CurrentPageIndex AndAlso i <= gridProducts.PageSize Then
                myList.Add(Me.Products(i))
            End If
        Next
        If myList.Count > 0 Then
            gridProducts.DataSource = myList
        End If
    End Sub
  
  
Private Property Products() As List(Of Product)
        Get
            Return CType(ViewState("Products"), List(Of Product))
        End Get
        Set(ByVal value As List(Of Product))
            ViewState("Products") = value
        End Set
    End Property
  
End Class

The paging at the bottom of my grid only shows 1 page but I have more products to display. Am I going about this the wrong way? Any help on this would be appreciated.

Thanks

9 Answers, 1 is accepted

Sort by
0
Accepted
Princy
Top achievements
Rank 2
answered on 18 Jan 2011, 08:30 AM
Hello Rob,

You are binding the grid in PageLoad event, which is Simple data binding technique. If you are using any advanced feature in grid(like filtering), then a better approach is using "AdvancedData binding" using NeedDataSource event.

For more information about this can be available here.
Advanced Data-binding (using NeedDataSource event)

Thanks,
Princy.
0
Rob Venable
Top achievements
Rank 1
answered on 19 Jan 2011, 04:16 AM
Hi Princy,
The link didn't work but I found another similar link and implemented the NeedDataSource.
Private Sub gridProducts_NeedDataSource(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles gridProducts.NeedDataSource
        
       Dim oProducts As New List(Of Product)
       oProducts = ProductBL.GetActiveProducts
       Dim startRowIndex As Integer = gridProducts.CurrentPageIndex * gridProducts.PageSize
       Dim maximumRows As Integer = gridProducts.PageSize
       Dim myList As New List(Of Product)
       For i As Integer = 0 To oProducts.Count - 1
           If i >= startRowIndex AndAlso i < maximumRows Then
               myList.Add(oProducts(i))
           End If
       Next
       If myList.Count > 0 Then
           gridProducts.DataSource = myList
       Else
           gridProducts.DataSource = oProducts
       End If
   End Sub

It fires on Page Load and it also fires when I change the page size and the correct number of Products display on my page. The only part that doesn't work is when I click on the Page Numbering or the arrows in the footer of the grid. The page numbers only show 1 and nothing fires when I click on the page number or the arrows. Right now, I only have the NeedDataSource firing...I'm not doing anything else in the page load or PageIndexChanged event. Any ideas why nothing happens when I click on the page numbers or arrows? My page size is set to 5 and I have 11 products so I should have 3 pages but I only show 1.

Thanks
0
Accepted
Pavlina
Telerik team
answered on 19 Jan 2011, 10:04 AM
Hello Rob,

To resolve the problem you should remove AllowCustomPaging property from the MasterTableView. Moreover, I followed your scenario and prepared a simple test project that is working as expected. Examine it and let me know if you need additional assistance.

All the best,
Pavlina
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
Rob Venable
Top achievements
Rank 1
answered on 20 Jan 2011, 12:44 AM
Hi Pavlina,
I set the AllowCustomPaging property to false and the page numbers now show up and work properly...but when I click on the arrows, I get the following error:
Server Error in '/' Application.
--------------------------------------------------------------------------------
  
Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
  
Exception Details: System.ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
  
Source Error: 
  
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  
  
Stack Trace: 
  
  
[ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
   System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +8628633
   System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +69
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +35
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
  
   
  
  
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.4952; ASP.NET Version:2.0.50727.4955

Any ideas? I also have a dropdowlist and a search box on my page to further filter the products.
0
Accepted
Pavlina
Telerik team
answered on 21 Jan 2011, 01:25 PM
Hi Rob,

Go through the following forum thread and see if it helps:
http://www.telerik.com/community/forums/aspnet-ajax/ajax/222106-invalid-postback-or-callback-argument.aspx

Regards,
Pavlina
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
Rob Venable
Top achievements
Rank 1
answered on 22 Jan 2011, 05:39 AM
Thanks Pavlina. My grid didn't have the ViewState enabled so I enabled it and now it works.

I have another question though and I'm hoping you may know the answer. The products are displaying properly and the paging is now working properly as well but I have a dropdown list where you can filter the products by category...Computer accessories, Jewelery etc... and the dropdown list was causing a postback and re-binding the grid with products by category ID. Do you know how I can implement this using the NeedDataSource or do I have a separate call to the database for this?

Thanks
0
Pavlina
Telerik team
answered on 25 Jan 2011, 01:30 PM
Hi Rob,

You can use the grid's PreRender event to specify an initial filter. Note that after setting the filter, you must rebind the grid:
http://www.telerik.com/help/aspnet-ajax/grdapplyingdefaultfilteroninitialload.html

Best wishes,

Pavlina
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
Rob Venable
Top achievements
Rank 1
answered on 29 Jan 2011, 11:47 PM
Hi Pavlina,
I've added this code to the grid's PreRender and it seems to be filtering properly
Private Sub gridProducts_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles gridProducts.PreRender
  
        If Not Page.IsPostBack Then
            If radCategories.SelectedValue <> String.Empty Then
                gridProducts.MasterTableView.FilterExpression = "([CategoryID] = " & radCategories.SelectedValue & ")"
                Dim column As GridColumn = gridProducts.MasterTableView.GetColumnSafe("CategoryID")
                column.CurrentFilterFunction = GridKnownFunction.Contains
                column.CurrentFilterValue = radCategories.SelectedValue
                gridProducts.MasterTableView.Rebind()
  
            End If
        End If
     End Sub

The only problem is when I filter by category and it return 6 products but my page's PageSize is set to 5 and when I click on the arrow for next page it should return me the 1 remaining item but it returns all remaining items regardless of the filter.
Any ideas?
0
Pavlina
Telerik team
answered on 02 Feb 2011, 02:33 PM
Hello Rob,

I tried to replicate the described issue but to no avail. Please find attached to this message a simple test project which is working as expected and let me know if it helps.

All the best,
Pavlina
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.
Tags
Grid
Asked by
Rob Venable
Top achievements
Rank 1
Answers by
Princy
Top achievements
Rank 2
Rob Venable
Top achievements
Rank 1
Pavlina
Telerik team
Share this question
or