Link to home
Start Free TrialLog in
Avatar of vinny45
vinny45

asked on

paging on a datalist with custom object(Arraylist) as datasource

i'm reading directory contents and populating the names of the files in an objectCollection that inherits from the arraylistclass and using it as a datasource for a datalist. How can I enable paging for this datalist. There is a lot of examples using the dataadapter, but i'm not connecting to a db. please advice
Avatar of davidlars99
davidlars99
Flag of United States of America image

I think for you to better understand paging without database would be to look at something that looks like a little shopping cart example, you can also use arrays for "Data Items" or you can even generate columns by "For.. Next" loop and put them into "DataSet" like so...  :)

----------------
example.aspx
----------------

<%@ Import Namespace="System.Data" %>
<%@ Page Language="VB" Debug="True" %>
<HTML>
<HEAD>
<Script Language="vb" Runat="Server">

Dim ds As DataSet, _
      dt As DataTable, _
      dc As DataColumn, _
      dr As DataRow, _
      PKColumn(1) As DataColumn
      
Private Sub Page_Load(s As Object, e As EventArgs)
      ds=New DataSet()
      dt=New DataTable("Cart")
      
      dc=New DataColumn("Item ID", GetType(Integer))
      dc.AutoIncrement=True
      dc.AutoIncrementSeed=1
      dc.AutoIncrementStep=1
      dc.Unique=True
      dt.Columns.Add(dc)
      PKColumn(0)=dc
      dt.PrimaryKey=PKColumn
      
      dc=New DataColumn("Item Name", GetType(String))
      dt.Columns.Add(dc)
      
      dc=New DataColumn("Quantity", GetType(Integer))
      dt.Columns.Add(dc)
      
      dc=New DataColumn("Price", GetType(Decimal))
      dt.Columns.Add(dc)
      
      dr=dt.NewRow()
      dr("Item Name")="Data Item 1"
      dr("Quantity")=1
      dr("Price")=19.99
      dt.Rows.Add(dr)
      
      dr=dt.NewRow()
      dr("Item Name")="Data Item 2"
      dr("Quantity")=1
      dr("Price")=49.99
      dt.Rows.Add(dr)
      
      dr=dt.NewRow()
      dr("Item Name")="Data Item 3"
      dr("Quantity")=1
      dr("Price")=69.99
      dt.Rows.Add(dr)
      
      dr=dt.NewRow()      
      dr("Item Name")="Data Item 4"
      dr("Quantity")=1
      dr("Price")=19.99
      dt.Rows.Add(dr)
      
      dr=dt.NewRow()
      dr("Item Name")="Data Item 5"
      dr("Quantity")=1
      dr("Price")=49.99
      dt.Rows.Add(dr)
      
      dr=dt.NewRow()
      dr("Item Name")="Data Item 6"
      dr("Quantity")=1
      dr("Price")=69.99
      dt.Rows.Add(dr)      
      
      dr=dt.NewRow()      
      dr("Item Name")="Data Item 7"
      dr("Quantity")=1
      dr("Price")=19.99
      dt.Rows.Add(dr)
      
      dr=dt.NewRow()
      dr("Item Name")="Data Item 8"
      dr("Quantity")=1
      dr("Price")=49.99
      dt.Rows.Add(dr)
      
      dr=dt.NewRow()
      dr("Item Name")="Data Item 0"
      dr("Quantity")=1
      dr("Price")=69.99
      dt.Rows.Add(dr)            
      
      ds.Tables.Add(dt)
      
      cart.DataSource=ds.Tables("cart").DefaultView
      cart.DataBind()
      
      Dim total As Decimal
      total=dt.Compute("Sum(Price)", Nothing)
      lblmsg.Text="Order Total: " & total.ToString()
End Sub

Private Sub BindData()
      cart.DataSource=ds.Tables("cart").DefaultView
      cart.DataBind()
End Sub

Private Sub dg_Paging(o As Object, e As DataGridPageChangedEventArgs)
      cart.CurrentPageIndex=e.NewPageIndex
      BindData()
End Sub

</Script>
<TITLE></TITLE>
</HEAD>
<BODY>

<form runat="server">
      <asp:datagrid id="cart" runat="server" autogeneratecolumns="true"
            allowpaging="true"
            pagesize="2"
            pagerstyle-mode="numericpages"
            onpageindexchanged="dg_Paging"
      />
      <br>
      <asp:label id="lblmsg" runat="server" />
</form>

</BODY>
</HTML>
try to change above datagrid with this

<asp:datagrid id="cart" runat="server" autogeneratecolumns="true"
      allowpaging="true"
      pagesize="2"
      pagerstyle-nextpagetext="Next &gt;"
      pagerstyle-prevpagetext="&lt; Prev"
      onpageindexchanged="dg_Paging"
/>


this will present paging with "Next... Prev..." link buttons
Avatar of vinny45
vinny45

ASKER

good examples but i need one for a datalist
like this..?


<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.IO" %>
<%@ Page Language="C#" Debug="True" %>
<html>
<script language="C#" runat="server">

string [] arr;

void Page_Load( Object sender , EventArgs e){
      arr=Directory.GetDirectories("C:\\Windows");
      if(!IsPostBack){
            Session["i"]=0;
            BuildGrid();
      }
}

public void BuildGrid(){      
      DataTable dt=new DataTable("Windows");
      DataColumn dc=new DataColumn("Item", Type.GetType("System.String"));
      dt.Columns.Add(dc);
      DataRow dr;
      int i;
            
      for (i=(int)Session["i"];i<((int)Session["i"]+(int.Parse(PageSize.Value)));i++){
            dr=dt.NewRow();
            dr["Item"]=arr[i];
            dt.Rows.Add(dr);
      }
    MyDataList.DataSource = dt;
    MyDataList.DataBind();

    TotalSize.Value=(arr.Length-2).ToString();
    lblmsg.Text="(Total Count: "+(arr.Length-2).ToString()+")";
  }

public void Page_DataList(object sender, EventArgs e){
    if(((LinkButton)sender).ID=="Prev"){
                  CurrentPage.Value=(int.Parse(CurrentPage.Value)-1).ToString();
                  Session["i"]=(int)Session["i"]-(int.Parse(PageSize.Value));
                  
    }
    else if(((LinkButton)sender).ID=="Next"){
                  CurrentPage.Value=(int.Parse(CurrentPage.Value)+1).ToString();
                  Session["i"]=(int)Session["i"]+(int.Parse(PageSize.Value));
    }
    BuildGrid();
}

 
</script>
<body>
<h3>Directory Listing <asp:label id="lblmsg" runat="server" /></h3>
<form runat="server">
      <asp:DataList id="MyDataList" RepeatColumns="1" RepeatDirection="Horizontal" runat="server">
            <ItemTemplate>
                  <%# DataBinder.Eval(Container.DataItem, "Item") %>
            </ItemTemplate>
</asp:DataList>

      <input type="hidden" id="PageSize" value="10" runat="server">
      <input type="hidden" id="CurrentPage" value="1" runat="server">
      <input type="hidden" id="TotalSize" runat="server">
      <br>
      <asp:LinkButton id="Prev" Text="<< Previous" OnClick="Page_DataList" runat="server" />
      &nbsp;
      <asp:LinkButton id="Next" Text="Next >>" OnClick="Page_DataList" runat="server" />
</form>
</body>
</html>
just makes sure you use correct directory path here

arr=Directory.GetDirectories("C:\\Windows");
I didn't pay attention at "Page_Datalist" sub you have to change it to this:



public void Page_DataList(object sender, EventArgs e){
    if(((LinkButton)sender).ID=="Prev"){
                  CurrentPage.Value=(int.Parse(CurrentPage.Value)-1).ToString();
                  if(((int)Session["i"]-(int.Parse(PageSize.Value)))<=0)
                        Session["i"]=0;
                  else
                        Session["i"]=(int)Session["i"]-(int.Parse(PageSize.Value));                               
    }
    else if(((LinkButton)sender).ID=="Next"){
                  CurrentPage.Value=(int.Parse(CurrentPage.Value)+1).ToString();
                  if(((int)Session["i"]+(int.Parse(PageSize.Value)))>=int.Parse(PageSize.Value))
                        Session["i"]=arr.Length-int.Parse(PageSize.Value);
                  else
                        Session["i"]=(int)Session["i"]+(int.Parse(PageSize.Value));
    }
    BuildGrid();
}
Avatar of vinny45

ASKER

this is what i ended up doing other solutions are very similar and might be better than mine.  there is a PagedDataSource (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwebuiwebcontrolspageddatasourceclasstopic.asp)  object that u fill with a datasource and you can set its propeties and bind it to a datalist: well heres the code

private void bind()
            {
                   //my custom object
                       PhotoGallery gallery = new PhotoGallery();
                       
                        //instantiate the pagedatasource obj
                  PagedDataSource objPds = new PagedDataSource();

                        //set the PhotoGallery  parameters to retrieve the info
                  gallery.Level = this.level;
                  gallery.PicturePath = this.picturePath;
                  gallery.Folder = this.folder;

                        //get the directory listing
                  objPds.DataSource = gallery.Fill(); //returns collection that inherits from the arraylist

                        //set the pagedatasource properites
                  objPds.AllowPaging  = true;
                  objPds.PageSize = 9;
                  objPds.CurrentPageIndex = CurrentPage;

                  lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of " 
                        + objPds.PageCount.ToString();

                  // Disable Prev or Next buttons if necessary
                  cmdPrev.Enabled = !objPds.IsFirstPage;
                  cmdNext.Enabled = !objPds.IsLastPage;
 
                  //bind the pagedatasource to the datalist
                  PortfolioDatalist.DataSource = objPds;
                  PortfolioDatalist.DataBind();

            }


            private void cmdPrev_Click(object sender, System.EventArgs e)
            {
                  // Set viewstate variable to the previous page
                  CurrentPage -= 1;

                  // Reload control
                  bind();
            }

            private void cmdNext_Click(object sender, System.EventArgs e)
            {
                  // Set viewstate variable to the next page
                  CurrentPage += 1;

                  // Reload control
                  bind();
            }

public int CurrentPage
            {
                  get
                  {
                        // look for current page in ViewState
                        object o = this.ViewState["_CurrentPage"];
                        if (o == null)
                              return 0;   // default to showing the first page
                        else
                              return (int) o;
                  }

                  set
                  {
                        this.ViewState["_CurrentPage"] = value;
                  }
            }

ASKER CERTIFIED SOLUTION
Avatar of davidlars99
davidlars99
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial