We help IT Professionals succeed at work.

Display 10 records at a time - repeater

azyet24
azyet24 asked
on
238 Views
Last Modified: 2012-06-21
I am pulling data (one field) from the database and need to display the results like this:

id1,id2,id3,id4,id5,id6,id7,id8,id9,id10
id11,id12.....
id21,id22...

I need to display 10 rows at a time.  If there are more than 10 available, then it needs to go to a nother line.  I'm clueless how to do this.  Can someone help me with this please...
Comment
Watch Question

version 2.0?

then use a datalist, and set these properties

DataList1.RepeatColumns = 10
DataList1.RepeatDirection = RepeatDirection.Horizontal

Praveen KumarArchitect

Commented:
Hope ur pulling data into a DataTable

Dim str As String

For i As Integer=0 To dtTable.Rows.Count-1
  str = str & dtTable.Row(i)(0)
  If( i >10 And i mod 10 = 0) Then str = str & vbCrLf
Next

Messagebox.Show(str)

Commented:
In the code benind

Dim MaxCols as Integer = 10
Dim itemCount as Long= 0

Function Next(byval sID as String) as String
    Dim currCol as Integer
    Dim s as new StringBuilder

    currCol = (itemCount mod MaxCols)
    itemCount += 1
   
    if currCol = 0 and itemCount > 1 then s.Append("</tr>")
    if currCol = 0 then s.Append("<tr>") 'open new row
    s.Append("<td align=center>").Append(sID).Append("</td>")

    return s.ToString()
End Function

In the design page

<form runat="server">
<asp:Repeater id="repeater1" runat="server">
<HeaderTemplate>
<table border="1" width="100%">
</HeaderTemplate>
<ItemTemplate>
<%# Next( Container.DataItem("idField") )%>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>

However, this is not tested on any server, and you need to improve the method to show the last </tr> for some cases.

Author

Commented:
This provides the rows with 10 listed but I need one more thing.  I need for each row to be one hyperlink like this:

http://www.domain.com/name1,name2,name3....name10
http://www.domain.com/name11,name12,name13....name20

here's what I have so far:

        <asp:DataList ID="DataList1" runat="server" RepeatColumns=10 DataSourceID="SqlDataSource1" RepeatDirection="Horizontal"
            ShowFooter="False" ShowHeader="False" DataKeyField="id" RepeatLayout="Flow">
            <ItemTemplate><%# Eval("name") %></ItemTemplate><SeparatorTemplate>,</SeparatorTemplate></asp:DataList>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:listingsConnectionString %>"
            ProviderName="<%$ ConnectionStrings:listingsConnectionString.ProviderName %>"
            SelectCommand="SELECT id,name FROM foreclosures"></asp:SqlDataSource>

I'm not sure how to make each row one hyperlink.
ah, now you throw in the monkeywrench...would have been really nice to know before hand... :)

I don't know if you can do that with a datalist, at least not super easily, that I know of... probably a way...I've just not done it.

maybe you're better off with using something like the repeater stuff gnoon suggested.

and, along with creating and ending each new row with a 'tr', also put in an 'a' (anchor) tag with that href...

but, the logic of building all the items in the list, is not going to be exactly trivial, and, if it were me, I guess I'd, not knowing a easy way to do this with list controls that come with asp.net, brute force it, and just write out the raw html myself.

or, use the datalist, come up with a scheme to build the links for each individual item that I could use to get the end result desired.

maybe something like making the href just have the name of the current item, and where it is in the list, like

http://www.domain.com/name11,1

next one

http://www.domain.com/name12,2

and use logic in the target, to get the right range of values...

or, maybe a better question, what are you going to do with this url? why does it 'need' the ten names?

might help to describe the entire 'story', so we don't end up at a dead end again.


Author

Commented:
Ok, good point.

There is a web site that will read the first items in the url (after the domain) and will display the items on the page.  I want to build urls that I can display where I can group items. So the link has to have commas between then and no more than 10 in each row.  I though about using a repeater but I didn't know how to limit the url to only 10 per row.
Could you just build the url for each item with the first name in the row?

Pass that on the URL, and have that target be smart enough to just grab that name, and know to start there and dislplay the next 10?

actually, to make it flexible, maybe you decide 10 is too many, or to few, or, you build the url so something like

http://www.domain.com/name11,10

start at name11, display the next 10?

or, more generically, start at this name, and display the next <<use value of DataList1.RepeatColumns here>>

then you could build the url to use the DataList1.RepeatColumns, and use logic to track the first item in each row, maybe like the other guys mod logic, and every time mod = 0, change the name to the current one, or???, I dunno, just looking for ideas.

would be better to find a way to make use of built in list controls, and make the target smart and flexible enough to handle many more usage scenarios if we're clever enough.

Author

Commented:
they url has to be domain.com/name1,name2,name3...name10 (where name is the field from the DB).  Could you show me how to do this..I'm not able to get this to work.
it is out of your control?

or you just made up your mind and won't change it?

the only way I can think of then, is to spin out the html yourself, and not use any of the built in controls.

post your code for this page you have so far then, and I'll see how much I can help.

Author

Commented:
Would it be possible to fill an array from the DB and then iterate through it that way?

Author

Commented:
I was thinknig that I could...

lblURL.Text = "<a href='http://www.domain.com/"
For i =0 to myarray.length  <-- this is where I'm lost, but it needs to be 10
lblURL.Text &= myarray(i) & ","
Next
lblURL.Text = "'>link name</a>"

Not sure how to fill an array from db to accomplish this but it seems like it should work. :)
ok, here is some code that will build the html in a table.

        Dim items As String() = New String() {"name1", "name2", "name3", "name4", "name5", "name6", "name7", "name8", "name9", "name10", "name11", "name12", "name13"}

        Dim tr As HtmlTableRow
        Dim td As HtmlTableCell
        Dim a As HtmlAnchor

        Dim i As Long
        i = 0

        While i < items.Length

            tr = New HtmlTableRow()
            td = New HtmlTableCell()
            a = New HtmlAnchor()

            a.HRef = "http://www.mydomain.com/"

            Do

                a.HRef &= items(i)
                a.InnerText &= items(i)

                If (Not (i + 1) Mod 10 = 9) And ((i + 1) < items.Length) Then
                    a.HRef &= ","
                    a.InnerText &= ","
                End If

                i += 1

            Loop Until (i + 1) Mod 10 = 0 Or i = items.Length

            td.Controls.Add(a)
            tr.Controls.Add(td)

            myGrid.Rows.Add(tr)

        End While

in the page, I have a plain old html table like this:
    <table id="myGrid" runat="server">
       
    </table>

Author

Commented:
awsome!  Care to share how I fill items from the database?

Commented:
You can apply my code above in many ways, here a sample

<form runat="server">
<asp:Repeater id="repeater1" runat="server">
<ItemTemplate>
    <%# Next("Items: <a href='http://www.domain.com/{0}'>{0}</a><br/>", 10, Container.DataItem("idField") )%>
</ItemTemplate>
</asp:Repeater>
</form>

and

Dim itemCount as Long= 0
Dim s as new StringBuilder

Function Next(ByVal format as String, ByVal MaxCols as Long, ByVal sID as String) as String

    Dim sRet as String = String.Empty
    Dim currCol = itemCount mod MaxCols
    if currCol = 0 and itemCount > 0 then
        sRet = String.Format(format, s)
        s.Length = 0 '--------------------------- reset for a new row
    end if

    if s.Length > 0 then s.Append(",")
    s.Append(sID)

    return sRet
End Function

Author

Commented:
gnoon, here's my code and error:

   Dim itemCount As Long = 0
    Dim s As New StringBuilder

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Fill Repeater
        Try
            objconn.Open()
            objCmd = New OdbcCommand("SELECT * FROM listings.foreclosures;", objconn)
            objRdr = objCmd.ExecuteReader()
            repeater1.DataSource = objRdr
            repeater1.DataBind()
        Catch ex As Exception
            ' lblError.Text = "An error has occured/"
            ' lblError.Text += ex.Message
        Finally
            objRdr.Close()
            objconn.Close()
        End Try
    End Sub
Function Next(ByVal format as String, ByVal MaxCols as Long, ByVal sID as String) as String
        Dim sRet As String = String.Empty
        Dim currCol = itemCount Mod MaxCols
        If currCol = 0 And itemCount > 0 Then
            sRet = String.Format(Format, s)
            s.Length = 0 '--------------------------- reset for a new row
        End If
        If s.Length > 0 Then s.Append(",")
        s.Append(sID)
        Return sRet
    End Function

Page:
<asp:Repeater id="repeater1" runat="server">
<ItemTemplate>
    <%# Next("Items: <a href='http://www.domain.com/{0}'>{0}</a><br/>", 10, Container.DataItem("name") )%>
</ItemTemplate>
</asp:Repeater>

Error:
BC30201: Expression expected. (at line <%# Next)

Commented:
How about

<%# Next("Items: <a href='http://www.domain.com/{0}'>{0}</a><br/>", 10, DataBinder.Eval(Container.DataItem,"name") )%>

Author

Commented:
Made the change and still got the same error.  Also, it was complaining about the reserved word Next.  So, I changed Next to Nextitem and now I no longer get any errors but not data is displayed in the repeater.  

Commented:
Oh! Yes, i forgot to increase the itemCount. Try to increase it in Nextitem just before the return.

Author

Commented:
gnoon,

This works, however if there is less than 10 items then it doesn't show anything.  What I'll have is maybe 5 or 15 or 30, etc... items so I'll need this to display no matter how many items I have, but no more than 10 per link (row).  Can your code be adjusted to accomodate this?

Commented:
The Nextitem will buffer items until reach 10, then flush to the page.
However, If the last set is not 10, it's not flushed. You need get the last set manually.

You may add a parameter to the Nextitem to force flush buffer, here

    Function Nextitem(ByVal format as String, ByVal MaxCols as Long, ByVal sID as String, ByVal forceFlush as Boolean) as String
        Dim sRet As String = String.Empty
        Dim currCol = itemCount Mod MaxCols
        If (currCol = 0 And itemCount > 0) or forceFlush Then
            sRet = String.Format(Format, s)
            s.Length = 0 '--------------------------- reset for a new row
        End If
        If s.Length > 0 and Not sID Is Nothing Then s.Append(",")
        if Not sID Is Nothing then s.Append(sID)
        itemCount += 1
        Return sRet
    End Function

in page

<form runat="server">
<asp:Repeater id="repeater1" runat="server">
<ItemTemplate>
    <%# Next("Items: <a href='http://www.domain.com/{0}'>{0}</a><br/>", 10, Container.DataItem("idField"), False )%>
</ItemTemplate>
</asp:Repeater>
    <%= Next("Items: <a href='http://www.domain.com/{0}'>{0}</a><br/>", 10, Nothing, True )%><br/>
</form>
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.