Skuffsworld

Web - Developer - Designer - Usability - Consultant

PagedDataSource in ASP.NET 2.0 Framework using VB.Net with an Repeater Control

clock June 25, 2009 15:22 by author Skuff

Ok, so during my time with Dot Net - which I love by the way - apart frrom when you want to do something slightly outside of DotNet logic - that...well thats when it get complicated

Anyway - I keep meaning to post something on my Blog every week but rarely get a chance to - been hellishly busy (good use of word hellishly there I thought).

So, something I find useful on occassion - PagedDataSource

Now, with the GridView approach (or DataGrid etc...) this is all build in and can be easily managed on the GridView control by simply adding AllowPaging=true - yes, it really is that simple, set a datasource to the gridview, bind it, allowpaging, set pagesize - theres enough properties available to keep you happy for hours. 

The only real issue I have hear is styling the BACK and NEXT paging controls and the pages available. Its not 100% perfect in a GridView - it should be easier - really it should be - its not like you can't style it to your hearts content - but sometimes you just want that bit more customisation.

So - I give you the PagedDataSource and in this example the Repeater control.

############### Lets begin

 

Lets start with  adding a Repeater control to the page and a Literal control which we will use to write a string value to show the end user what page they are on and how many pages there are.

 

<asp:Literal ID="lit_Pages" runat="server" /> 

<asp:Repeater ID="rpt" runat="server">

<ItemTemplate>

  <!-- put your databound items in here -->

<%#Eval("A_Data_Bound_Item")%> 

</ItemTemplate>

        </asp:Repeater>

 

Easy - so now you need to bind your data to this control - lets go to the code behind for this :) Now, I normally used a class I created which controls PagedDateSources which I can call in any page and set a few properties, but in this example I will create a method which is called from the Page_Load method.

 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
       If Not Page.IsPostBack Then
 'is no post back occured 
            bindPagedDS() 'onlys runs at intial load of page

End If

    End Sub 

 

Once this is done you will need to add a property (could be a method if you wanted) to store the CURRENT page index that an end user is viewing, i.e. page 1 of 10

This is simple.

 

'a variable for the name of the item in ViewState that you will store CurrentPageIndex to. 

Public pdsName As String = "ViewState_PagingSource_Name"

    ''' <summary>
    ''' Stores current page in repeater paging to viewstate
    ''' </summary>
    ''' <param name="vsName">String. Name of viewstate key.</param>
    ''' <value></value>
    ''' <returns>Integer. The current page number</returns>
    ''' <remarks></remarks>
    Public Property CurrentPage(ByVal vsName As String) As Integer
        Get
            Dim o As Object = Me.ViewState(vsName)
            If o Is Nothing Then
                Return 0
            Else
                Return Convert.ToInt32(o)
            End If
        End Get
        Set(ByVal value As Integer)
            Me.ViewState(vsName) = value
        End Set
    End Property 

 

   ''' <summary>
    ''' Creates PagedDataSource object
    ''' </summary>
    ''' <remarks></remarks> 
    Public Sub bindPagedDS()
        Dim pds As New PagedDataSource
 Dim dt as New DataTable 
  dt = A_Collection_Of_Data 'whatever you require this to be, a database create datatable, some XML, whatever  
 
       pds.DataSource = dt 'your data
        pds.PageSize = "10" 'any integer you require
        pds.CurrentPageIndex = Me.CurrentPage(pdsName) 'store the CurrentPageIndex in viewstate - nice
        pds.AllowPaging = True 'yep, set paging on this bad boy

        Me.cmdBack.Visible = Not pds.IsFirstPage 'if its NOT first page - which mean - if it is first page return TRUE so NOT TRUE is false :)
        Me.cmdNext.Visible = Not pds.IsLastPage 'see above comment numbnuts

        Me.lit_Pages.Text = (pds.CurrentPageIndex + 1) & " of " & pds.PageCount 'set text of Literal control to page info        rpt.DataSource = pds 'set the Repeater data source to the PagedDataSource we have just created
        rpt.DataBind() 'bind it stoooopid

    End Sub 

Right, now we have binded the data to the Repeater we know that we want a BACK and NEXT button which we can customise - so lets a couple ifLinkButtons onto the page at design level (can be any submit control - such as Button or ImageButton).

We also want to set the Command property on each LinkButton to called a custom method to handle the BACK and NEXT operations. I use this as its a method I can apply to both of the LinkButtons and action paging BACK or NEXT via a CommandArgument which for BACK is '-' (negative/minus symbol) and '+' (positive/add symbol)

 

<asp:LinkButton ID="lnkBtn_Back" runat="server" Text="&lt;&lt; Back" OnCommand="actionPaging"  CommandArgument="-" />  

&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;  

<asp:LinkButton ID="lnkBtn_Next" runat="server" Text="Next &gt;&gt;" OnCommand="actionPaging"  CommandArgument="+" />  

 

Once we have added this to the LinkButton controls at design level we are ready to add a method to handle the Command for each of them. So, in the code behind add another method:

 

     ''' <summary> 

    ''' Actions a paging request. BACK or NEXT page

    ''' </summary>

    ''' <param name="sender">LinkButton. The control clicked,.</param>

    ''' <param name="e">CommandEventArgs. Command event arguments.</param>

    ''' <remarks></remarks>

    Public Sub actionPaging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs)

      'now we must check what the CommandArgument value is and perform a increment or subtraction accordinly

 If e.CommandArgument = "-" Then

            'is back on page - MINUS

            Me.CurrentPage(pdsName) -= 1 'store the NEW page number in viewstate

        Else

            'assume next page - ADD

            Me.CurrentPage(pdsName) += 1 'store the NEW page number in viewstate

        End If

  'this method can only occur on postback so now we re-bind the data 

        bindPagedDS() 'now rebind the data dummy :)

    End Sub 

  ############### Thats it

 Pretty easy hey - I have only covered the PagedDataSource in as a quick guide to getting you started - just allows for ease of customisation over GridViews - and look into caching the data to improve performance (unless you will be updating records in this view - in which case why aren't you using a GridView ;-) )

 

 

 

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Latest Vodafone project - Bespoke DotNet Blog engine for the masses - well, us anyway!

clock April 30, 2009 15:46 by author Skuff

A couple ago weeks I released a Vodafone Specialist Communications Blog web app.

 Now, there are loads of free blog engines you can use - this site itself is using of of said blog engines - indeed BlogEngine.Net!

So why would I build one? good question Holmes. Well, out lovely IT team setup our web servers to be clustered - which makes sense - of course. However - this means any data source realistically has to be a database - in our case a SQL server 2005.

Most free blog engines use XML to store blog posts and comments etc... which causes a huge problem in a clustered server environment.  The data will save onto the web server you have been sent to - so any post you make will be on Server A for example while Server B is completely oblivious to your post - so you need t sync - I'm not going down that route.

There were also some blgo engines that offered a database solution but the actual blog engine itself was a bit lousey to say the least. 

Tasked I was with a building a blog engine - quickly at that! see http://www.vodafonerental.com/blog  il talk about URL rewriting in Asp.Net 2.0 another times, its not easy when theres not file or extension on the URL - ASP.Net 3.5 apparently has sorted it out - nice - but believe me, in 2.0 its a nightmare t get true URL rewriting - you need magicians and a hell of a lot of patience to find the right solution - I did and will share - its based on Apaches wonderfull htaccess (i think - don't quote me) approach.

So here it is.... http://www.vodafonerental.com/blog  which we just push a PR campaign to on one of our posts (got over 7000 unique visits - one error recorded, and I think that was me to be fair - i was happy) - as we are launching to BlackBerry Storm in to out American rental fleet - nice.... its really that not bad the Storm - it got panned - by the "apple loving, microsoft hating, linux loving - oh god isn't php the best thing ever - and what about ruby on rails?" - actually ruby on rails looks pretty sweet - don't think it will ever rival DotNet as hoped - but still, framework wise looks nice - can't be bothered to learn it though - too much in DotNet to learn... where was I?

Oh yes... the BlackBerry Storm - honestly -I wasn't a fan either, I was trialling it and found it difficult to use - the learning curve with the screen was the hard bit and how to "use" it. A week or so later - loved it - its a great smartphone... really, I don't have one, I have the Samsumg Omnia - which I love - but given the choice yes, I would have the iPhone - im no fool - altho copy and paste people -= copy and paste - seriously!!! No MMS either? I'm sorry did we go back in time to the stoneage? No, Apple are a little too big for their boots I reckon - think about - they keep interest and demand by releasing products and devices which do so many amazing thing - ah, wait... iPhone 1 doesn't have 3G - thats not right is it? Seriously - no, can't be. Wheres MMS? what the?! Hello - email... hello!!!

 Heres to iPhone 2! Ok, so the masses go and get that... wait - whats up with this camera? its lame? Still no MMS? Copy and paste is still missing? 3G isn't strictly 3G - honestly, its not. But still it is a wonderful phone... it really is.... hang on, isn't the iphone 3 coming? Taking bets on whats missing on that baby - HSDPA? a decent camera? MMS? Come on, surely they'll add that - won't they?

Blah Blah Blah Blah - I hate marketing, people who work in marketing and the word marketing.... signing off :)

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


How to transform XML with XSL in Asp/VB.Net 2.0

clock December 17, 2008 12:56 by author Skuff

About time I started posting something on here really! Here goes, well, its a start anyway.

There are various techniques for transforming XML with XSL. For starters this assume you have an understanding of the basic principles and techniques of XSL - if not - see W3 Schools and for a reference (the holy bible of XSL as it were) see Mulberry Technologies for more information. Its the best source for all things XSL and XPATH.

First, it depends of if the XML is local or external. Ifs local you have a few options, the quickest and easiest way to transform is is to use an ASP XML control on the page, you can then transform and bind the data from design mode or code behind.

[code] 

Add XML control to the page and bind at design level: 

<asp:Xml ID="xml_Control" runat="server" TransformSource="App_Data/SomeXMLDoc.xml" DocumentSource="XSL/SomeXSLDoc.xsl" />

  OR add XMLDoc and XSLDoc from code behind:

<asp:Xml ID="xml_Control" runat="server" />

CODE BEHIND: 

me.xml_Control.DocumentSource = "~/App_Data/SomeXML.xml"

me.xml_Control.TransformSource = "~/XSL/SomeXSLDoc.xsl"

me.xml_Control.DataBind() 

[/code] 

The code above is the quickest way to do this. In DotNet 2.0 they say use their new compiled transform method (which is very useful for assigned the returned data from the XML/XSL transform to a StringBuilder) as inconsistancies in XSL recursion (I'm sure many XSL gurus will know the joy of XSL recursion) can occur - however for everything else the above method works fine.

What about XML Transform Arguments List?

To add an XML arguments list to be used in the XSL you need to add this to the XML control from the code behind. This arguments list are refered to as parameters in your XSL document which you can use as you require (getting a specific node by attribute value, i.e. an ID value).

Another extremely power aspect of DotNet with XML and XSL is being able to pass in an ExtensionObject which allows you to create a namespace in the XSL which you can use to reference methods in a class you have created (such as XSLFunctions etc...) 

  [code] 

Dim xmlArgs As New System.Xml.Xsl.XsltArgumentList

Dim XSL_NS As New XSLFunctions 'a class I have created contained methods/functions

xmlArgs.AddParam("ParamName1", "", "Param1Value")

xmlArgs.AddParam("ParamName2", "", "Param2Value")

 

So the full code would now be (assuming you are doing this ALL in the code behind): 

  me.xml_Control.DocumentSource = "~/App_Data/SomeXML.xml"

me.xml_Control.TransformSource = "~/XSL/SomeXSLDoc.xsl"

me.xml_Contro.TransformArgumentList = xmlArgs 

me.xml_Control.DataBind()  

  [/code] 

Depending upon how much you use XML/XSL transforms you should really look at a class that contains all the methods to do this for you, returning a simple string/boolean valued error message (or some other object response) to inform the user of whats going on - either display the data or let them know (in a friendly way) that there has been an error - of course DotNet allows you so much control in error handling - but thats a different matter. 

NB: always use Try, Catch, Finally & End :)

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


About the author

I work for Vodafone Specialist Communications as a Asp.Net developer. I am also a bass player and hold my own acoustic gigs which I broadcast live via a webcast at Sunday Cellar. I also have a photo blog at Skuffsworld Photo Blog. I am also available for private development and design work please contact me with any questions.

Page List

Sign in