[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2004-11-23
8
Medium Priority
?
549 Views
Last Modified: 2012-05-05
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
0
Comment
Question by:vinny45
  • 6
  • 2
8 Comments
 
LVL 13

Expert Comment

by:davidlars99
ID: 12662043
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>
0
 
LVL 13

Expert Comment

by:davidlars99
ID: 12662053
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
0
 

Author Comment

by:vinny45
ID: 12663965
good examples but i need one for a datalist
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 13

Expert Comment

by:davidlars99
ID: 12668802
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>
0
 
LVL 13

Expert Comment

by:davidlars99
ID: 12668810
just makes sure you use correct directory path here

arr=Directory.GetDirectories("C:\\Windows");
0
 
LVL 13

Expert Comment

by:davidlars99
ID: 12669176
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();
}
0
 

Author Comment

by:vinny45
ID: 12669615
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;
                  }
            }

0
 
LVL 13

Accepted Solution

by:
davidlars99 earned 1500 total points
ID: 12671435
glad you've found something, but that seems a bit confusing, here is really cool one:



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

void Page_Load( Object sender , EventArgs e){      
      if(!IsPostBack){
            string [] arr=Directory.GetDirectories("C:\\");
            Session["folders"]=arr;
            Session["i"]=0;
            Session["j"]=(int.Parse(PageSize.Value));
            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["j"]);i++){
            dr=dt.NewRow();
            dr["Item"]=((string[])Session["folders"])[i];
            dt.Rows.Add(dr);
      }
    MyDataList.DataSource = dt;
    MyDataList.DataBind();
    TotalSize.Value=(((string[])Session["folders"]).Length).ToString();
    lblmsg.Text="(Total Count: "+(((string[])Session["folders"]).Length).ToString()+")";
}
public void Page_DataList(object sender, EventArgs e){
    if(((Button)sender).ID=="Prev"){
                  CurrentPage.Value=(int.Parse(CurrentPage.Value)-1).ToString();
                  if(((int)Session["i"]-(int.Parse(PageSize.Value)))<0){
                        Session["i"]=0;
                        Session["j"]=(int.Parse(PageSize.Value));
                        Prev.Enabled=false;
                        Next.Enabled=true;
                  }else{
                        Session["i"]=(int)Session["i"]-(int.Parse(PageSize.Value));
                        Session["j"]=(int)Session["i"]+(int.Parse(PageSize.Value));
                        Prev.Enabled=true;
                        Next.Enabled=true;
                  }                              
    }
    else if(((Button)sender).ID=="Next"){
                  CurrentPage.Value=(int.Parse(CurrentPage.Value)+1).ToString();
                  if(((int)Session["j"]+(int.Parse(PageSize.Value))) > (((string[])Session["folders"]).Length)){
                        Session["i"]=(int)Session["j"];
                        Session["j"]=(((string[])Session["folders"]).Length);
                        Next.Enabled=false;
                  }else{
                        Session["i"]=(int)Session["j"];
                        Session["j"]=(int)Session["i"]+(int.Parse(PageSize.Value));
                        Next.Enabled=true;
                        Prev.Enabled=true;
                  }
    }
    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="5" runat="server">
      <input type="hidden" id="CurrentPage" value="1" runat="server">
      <input type="hidden" id="TotalSize" runat="server">
      <br>
      <asp:Button id="Prev" Text="<< Prev" OnClick="Page_DataList" runat="server" />
      &nbsp;
      <asp:Button id="Next" Text="Next >>" OnClick="Page_DataList" runat="server" />
</form>
</body>
</html>
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
This article was originally published on Monitis Blog, you can check it here . Today it’s fairly well known that high-performing websites and applications bring in more visitors, higher SEO, and ultimately more sales. By the same token, downtime…
Any person in technology especially those working for big companies should at least know about the basics of web accessibility. Believe it or not there are even laws in place that require businesses to provide such means for the disabled and aging p…
The viewer will get a basic understanding of what section 508 compliance can entail, learn about skip navigation links, alt text, transcripts, and font size controls.
Suggested Courses
Course of the Month18 days, 10 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question