Index a repeater – pretty simple

by Andrei Hetel 6. February 2008 12:45

Piece of code presented here simply add a column, not related with content of the repeater, which index current line of data.
Repeater definition:

 

<asp:Repeater id="RB" runat="server">
  <HeaderTemplate>
    <tr>
      <td align="right">#</td>
      <td>User</td>
      <td align="right">Points</td>
    </tr>
  </HeaderTemplate>
  <ItemTemplate>
    <tr>
      <td align="right"><asp:Label ID="t5" runat="server"></asp:Label></td>
      <td><%#DataBinder.Eval(Container.DataItem, "UserName")%></td>
      <td align="right"><%#DataBinder.Eval(Container.DataItem, "TotalPoints")%></td>
    </tr>
  </ItemTemplate>
</asp:Repeater>

 

In code behind, first declare a variable:

 

Private CounterOverallTop As Integer = 1

 

Don’t forget to bind your data to the repeater, something like:

RB.DataSource = … your data source RB.DataBind()

 

Following code will populate index column.

 

Protected Sub RB_ItemDataBound(ByVal sender As Object, _
                                                   ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) _
                                                   Handles RB.ItemDataBound

  If (e.Item.ItemType = ListItemType.Item) Or _
    (e.Item.ItemType = ListItemType.AlternatingItem) Then

      DirectCast(e.Item.FindControl("t5"), Label).Text = CounterOverallTop
      CounterOverallTop += 1

  End If

End Sub

 

Paging in SQL Server 2005

by Andrei Hetel 1. February 2008 11:46

Let’s suppose that we want to have a page that will display top users, ordered by number of points. A simplified table named Users with only 3 columns looks like that: UserId INT primary key, LoginName Varchar, OverAllPoints INT.
First of all we need a view which calculates the rank of every user according to number of points:

 

CREATE VIEW UsersTop AS
SELECT
RANK() OVER (ORDER BY OverAllPoints DESC, LoginName) AS RankPoints,
UserId, LoginName, OverAllPoints
FROM Users

 

Based on the view created above, we can get for example the rank of any user:

 

SELECT RankPoints
FROM UsersTop
WHERE UserId = @userId

 

Another useful piece of code, presented below is returning all the users between a start row and end row. Assuming that you want to display page 3 from your top users, and on every page 20 lines are displayed, then stored procedure can be called like that:

 

EXEC UsersMyTop 41,60

 

CREATE PROCEDURE UsersMyTop
(@startRow INT, @endRow INT)
AS
BEGIN
SET NOCOUNT ON
SELECT
UserId, LoginName, OverAllPoints, RowNumber
FROM
(SELECT
U.UserId, U.LoginName, U.OverAllPoints,
ROW_NUMBER() OVER(ORDER BY U.OverAllPoints DESC, U.LoginName) AS RowNumber
FROM
Users U ) DerivedTable
WHERE RowNumber >= @startRow AND RowNumber <= @endRow
ORDER BY OverAllPoints DESC

END