?
Solved

paging help - urgent!!

Posted on 2004-10-20
21
Medium Priority
?
296 Views
Last Modified: 2008-02-01
I am trying to build a custom numeric pager for my datagrid.

Here is where I am buidling my string and outputting it to an asp.net label.

public void DisplayPager()
{

                  
int _totalPages = totalRecords/pageSize;
StringBuilder pager = new StringBuilder("Page: ");
for(int i=1; i < _totalPages+1;i++)
{
   if (i==datagrid.CurrentPageIndex+1)
   {
      //no hyperlink
      pager.Append(String.Format("{0} ", i.ToString()));
   }
   else
   {
      //need hyperlink
      pager.Append(String.Format("<a href=\"javsascript:__doPostBack('Grid_OnPageIndexChanged',{0});\" class='link-green'   runat='server'>{0}</a> ", i.ToString()));
    }
}
lblPaging.Text = pager.ToString();
}

My the link needs to call the following function, "OnPageIndexChanged" which will update the datagrids page index and pull the correct data. I am trying to use the asp.net __doPostBack functions for this, as you saw in the code above.

protected void OnPageIndexChanged(Object sender, DataGridPageChangedEventArgs e)
{
this.findMeetingDG.CurrentPageIndex = e.NewPageIndex;
LoadGrid();
}

I have been trying to figure this out for about a week and cannot!! I would appreciate any help in accomplishing this task.

thanks
0
Comment
Question by:jrmcdona
  • 7
  • 6
  • 5
  • +1
21 Comments
 
LVL 11

Expert Comment

by:sachiek
ID: 12365579
Sorry, I could'nt get you.

What is that you exactly want to do?

Paging? Or are you geting any error if soo pls put the error here.

Sachi
0
 
LVL 18

Expert Comment

by:tusharashah
ID: 12365737
hi jrmcdona,

Let me suggest one alternative approach then the way you are trying. How about passing the PageNumber as QueryString?

//need hyperlink // Modify this line from one you shown...
  pager.Append(String.Format("<a href='" + Request.Url.AbsolutePath + "?PageNo={0}' class='link-green'>{0}</a> ", i.ToString()));

& in your LoadGrid() before you Bind your Grid add following line

public void LoadGrid()
{
   ....
   ....
   if( Request.QueryString["PageNo"] != null )
   {
      DataGrid1.CurrentPageIndex = Convert.ToInt32( Request.QueryString["PageNo"] ) - 1;
   }
   else
   {
       DataGrid1.CurrentPageIndex = 0;
    }
   DataGrid1.DataBind();
}


-tushar
0
 

Author Comment

by:jrmcdona
ID: 12366111
thanks tushar, I think this could work good!

However, I am getting one error now after implementing this.

Where is the PageCount set, I cannot figure that part out yet to help me fix the error!
  "Invalid CurrentPageIndex value. It must be >= 0 and < the PageCount."

thanks again!

 
 
 
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:jrmcdona
ID: 12366182
it appears my PageCount is always 0 when i write it out on the page. Though I dont see anyway to change it since it is read only?

thanks
0
 
LVL 11

Expert Comment

by:sachiek
ID: 12366287
Well, why dont you run through debug mode.

Keep a break point in below line.

  pager.Append(String.Format("{0} ", i.ToString()));

 Check what is really appended.

Sachi
0
 

Author Comment

by:jrmcdona
ID: 12366349
thanks for the suggestion, My string is appending just fine.

When the page loads, everything works. However, when I click on the Page 2 link it breaks with the error I mentioned above.

0
 
LVL 11

Expert Comment

by:sachiek
ID: 12367687
I again want you to go through debuging and see what is there while you got to page 2.

Did you checked that?

Sachi
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12368872
right before you bind your data to the datagrid put:

mydatagrid.CurrentPageIndex = 0

Aeros
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12368876
I think in C# it would be:

mydatagrid.CurrentPageIndex = 0;
0
 
LVL 18

Expert Comment

by:tusharashah
ID: 12368926
I believe you are getting that error because of Empty( or smaller) DataSet.
When exactly in your code are you getting this message?
  "Invalid CurrentPageIndex value. It must be >= 0 and < the PageCount."

If you are modifying your DataSet somewhere (may be filter!) then Change QueryString to 0 at that time & start fresh for new DataSet

-tushar
0
 

Author Comment

by:jrmcdona
ID: 12371336
The DataGrid.DataBind() is causing this error. I dont have any filters and I am calling the same function to get my dataset. I can see that when I call the dataset on page 2, it still has 6 rows total, like it did on page 1.

AerosSaga, if I add mydatagrid.CurrentPageIndex = 0; right before I bind the data, then I will never be able to get to the second page, the data will always displays page 1 data.

Here is the complete method. Maybe I just missing something, but I tried several things last night and failed! Thanks for your help with this.

private void LoadMeetings()
{
{
LMUser User = Session["LMUser"] as LMUser;

DataTable dt = this.PageController.LoadMeetings(User);

if (dt == null)
{
lblNoGridData.Visible = true;
findMeetingDG.Visible = false;
lblNoGridData.Text = "You have no main meetings.";
}
else
{            
lblNoGridData.Visible = false;
findMeetingDG.Visible = true;

if( Request.QueryString["PageNo"] != null )
{
findMeetingDG.CurrentPageIndex = Convert.ToInt32(Request.QueryString["PageNo"]) - 1;
}
else
{
findMeetingDG.CurrentPageIndex = 0;
}

                              
DataView dv = new DataView(dt);

this.findMeetingDG.DataSource = dv;
this.findMeetingDG.DataBind();
Label1.Text = findMeetingDG.PageCount.ToString();
}
}
catch(Exception e)
{
lblPageError.Text = e.Message.ToString();
}
}

0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12371349
I thought you just said you weren't using paging????
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12371363
oh sorry diregard post was for another question.
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12371365
let me post my code for you.
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12371375
<asp:datagrid id="Products" runat="server" Width="550px" BorderColor="DarkGray" AutoGenerateColumns="False"
                                          CellPadding="5" GridLines="Horizontal" AllowPaging="True" BorderWidth="1px">
                                          <AlternatingItemStyle BackColor="White"></AlternatingItemStyle>
                                          <ItemStyle BackColor="WhiteSmoke"></ItemStyle>
                                          <HeaderStyle Font-Bold="True"></HeaderStyle>
                                          <Columns>
                                                <asp:TemplateColumn HeaderText="Product Name">
                                                      <HeaderStyle Width="440px"></HeaderStyle>
                                                      <ItemTemplate>
                                                            <asp:Label id="ProductInfo" runat="server"></asp:Label>
                                                      </ItemTemplate>
                                                </asp:TemplateColumn>
                                                <asp:TemplateColumn>
                                                      <ItemStyle HorizontalAlign="Right"></ItemStyle>
                                                      <ItemTemplate>
                                                            <asp:LinkButton id="EditItem" runat="server" CommandName="Edit">Edit</asp:LinkButton>&nbsp;&nbsp;&nbsp;
                                                            <asp:LinkButton id="DeleteItem" runat="server" CommandName="Delete">Delete</asp:LinkButton><INPUT id="ItemImageSrc" type="hidden" size="1" runat="server" NAME="ItemImageSrc">&nbsp;
                                                      </ItemTemplate>
                                                </asp:TemplateColumn>
                                          </Columns>
                                          <PagerStyle PageButtonCount="20" Mode="NumericPages"></PagerStyle>
                                    </asp:datagrid>

Private Sub Products_ItemDataBound(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles Products.ItemCreated
        Dim DeleteItem As LinkButton
        Dim ProductName As Label
        Dim ImageSrc As HtmlInputHidden
        If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then

            DeleteItem = DirectCast(e.Item.FindControl("DeleteItem"), LinkButton)
            DeleteItem.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this " & _
                "product?');")

            ProductName = DirectCast(e.Item.FindControl("ProductInfo"), Label)
            ProductName.Text = CStr(DataBinder.Eval(e.Item.DataItem, "ProductName"))
            ProductName.Text &= "<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#187; " & _
                CStr(DataBinder.Eval(e.Item.DataItem, "Tier1Name"))
            If Not DataBinder.Eval(e.Item.DataItem, "Tier2Name") Is DBNull.Value Then
                ProductName.Text &= "&nbsp;&#187;&nbsp;" & CStr(DataBinder.Eval(e.Item.DataItem, "Tier2Name"))
            End If
            If Not DataBinder.Eval(e.Item.DataItem, "Tier3Name") Is DBNull.Value Then
                ProductName.Text &= "&nbsp;&#187;&nbsp;" & CStr(DataBinder.Eval(e.Item.DataItem, "Tier3Name"))
            End If

            ImageSrc = DirectCast(e.Item.FindControl("ItemImageSrc"), HtmlInputHidden)
            ImageSrc.Value = CStr(DataBinder.Eval(e.Item.DataItem, "ImageSrc"))
        End If
    End Sub
    Private Sub Products_ItemCommand(ByVal source As System.Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles Products.ItemCommand
        If Not Page.IsPostBack Then Return

        If e.CommandName = "Delete" Then
            Dim cnn As New OleDb.OleDbConnection(ConfigurationSettings.AppSettings("SiteDB"))
            Dim cmd As New OleDb.OleDbCommand
            Dim ImageSrc As String = DirectCast(e.Item.FindControl("ItemImageSrc"), HtmlInputHidden).Value
            Dim ProductImage As IO.FileInfo

            cmd.CommandType = CommandType.Text
            cmd.CommandText = "DELETE FROM Products WHERE ProductID = " & _
                CStr(Products.DataKeys(e.Item.ItemIndex))
            cmd.Connection = cnn

            cnn.Open()
            cmd.ExecuteNonQuery()
            cnn.Close()

            cmd.Dispose()
            cnn.Dispose()

            Try
                ProductImage = New IO.FileInfo(Server.MapPath("~/Pictures/Products/" & ImageSrc))
                If ProductImage.Exists Then ProductImage.Delete()
                ProductImage = New IO.FileInfo(Server.MapPath("~/Pictures/Products/Thumbnails/" & ImageSrc))
                If ProductImage.Exists Then ProductImage.Delete()
            Catch ex As Exception

            End Try

            LoadProductData()
        ElseIf e.CommandName = "Edit" Then
            Response.Redirect("EditProduct.aspx?pid=" & CStr(Products.DataKeys(e.Item.ItemIndex)))
        End If
    End Sub
    Private Sub Products_PageIndexChanged(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles Products.PageIndexChanged
        Products.CurrentPageIndex = e.NewPageIndex
        LoadProductData()
    End Sub
    Private Sub LoadProductData(Optional ByVal Query As String = "")
        Dim cnn As New OleDb.OleDbConnection(ConfigurationSettings.AppSettings("SiteDB"))
        Dim cmd As New OleDb.OleDbCommand
        Dim da As New OleDb.OleDbDataAdapter(cmd)
        Dim dt As New DataTable

        'If the query is not passed, check to see if a previous query has been executed and stored
        If Query = "" Then Query = FullQuery.Value

        'If it's still empty, use the default query
        If Query = "" Then
            Query = "SELECT Tier1.Name AS Tier1Name, Tier2.Name AS Tier2Name, Tier3.Name AS Tier3Name, " & _
                "Products.Name AS ProductName, Products.ProductID, Products.ImageSrc FROM Tier3 RIGHT " & _
                "JOIN (Tier2 RIGHT JOIN (Tier1 INNER JOIN Products ON Tier1.Tier1ID = Products.Tier1ID) " & _
                "ON Tier2.Tier2ID = Products.Tier2ID) ON Tier3.Tier3ID = Products.Tier3ID ORDER BY " & _
                "Products.Name"
        End If

        cmd.CommandType = CommandType.Text
        cmd.CommandText = Query
        cmd.Connection = cnn

        da.Fill(dt)

        Products.DataKeyField = "ProductID"
        Products.DataSource = dt
        Products.DataBind()

        cmd.Dispose()
        cnn.Dispose()

        If Products.Items.Count = 0 Then
            Products.Visible = False
        Else
            Products.Visible = True
        End If
    End Sub

Private Sub SearchProducts_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchProducts.Click

        QueryValidator.Enabled = True
        Tier1Validator.Enabled = False
        ProductNameValidator.Enabled = False
        Validate()

        If Not IsValid Then Return

        Dim Query As String

        Query = "SELECT Tier1.Name, Tier2.Name, Tier3.Name, Products.Name, Products.ProductID " & _
            "FROM Tier3 RIGHT JOIN (Tier2 RIGHT JOIN (Tier1 INNER JOIN Products ON Tier1.Tier1ID = " & _
            "Products.Tier1ID) ON Tier2.Tier2ID = Products.Tier2ID) ON Tier3.Tier3ID = " & _
            "Products.Tier3ID WHERE "

        Select Case FieldsToMatch.SelectedValue
            Case "ProductName"
                Query &= "ProductName LIKE '%" & SearchQuery.Text & "%'"
            Case "Description"
                Query &= "Products.Description LIKE '%" & SearchQuery.Text & "%'"
            Case "Either"
                Query &= "Products.Description LIKE '%" & SearchQuery.Text & "%' OR ProductName LIKE '%" & _
                    SearchQuery.Text & "%'"
        End Select
        Query &= " ORDER BY Products.Name"
        LoadProductData(Query)
        FullQuery.Value = Query
0
 
LVL 18

Expert Comment

by:tusharashah
ID: 12371407
When this code is being called, what dose query string says? Make sure it's starting from 1 or take -1 from following code.

if( Request.QueryString["PageNo"] != null )
{
findMeetingDG.CurrentPageIndex = Convert.ToInt32(Request.QueryString["PageNo"]) - 1;
}
else
{
findMeetingDG.CurrentPageIndex = 0;
}

-tushar
0
 

Author Comment

by:jrmcdona
ID: 12371605
Tushar, when I click on the Page 2 link, I am passing in a value of 2 for the "PageNo" querystring.  For some reason, my DataGrid.PageCount is never changing from the value of 1 and I have 3 pages? So when I click on Page 2(CurrentPageIndex=1) the value equals that of the PageCount causing it to fail.

I have ViewState turned on and it is necessary for my page. Surely its not caching the DataGrid.PageCount.

AerosSage, I will look at your code, though it looks like you are displaying the Pager in the DataGrid footer where as I am creating my own label and placing it outside of the Datagrid.

thanks!
0
 

Author Comment

by:jrmcdona
ID: 12371621
One other thing, could this have anything to do that my links are not PostBacks? The links are just hyperlinks calling the page again and I am loading the DataTable on page load each time

0
 
LVL 18

Accepted Solution

by:
tusharashah earned 2000 total points
ID: 12372272
It seems like you have Check "Allow custom paging"

In this method we are using the inbuilt paging with our call. So, Un-Check "Allow custom paging" if you have checked it.

The Settings should look like following:
  DataGrid -> Property Builder -> Paging
  Allow paging (Checked)
  Allow  custom paging (Un checked)
  Show navigation  button (un-checked)

-tushar
0
 

Author Comment

by:jrmcdona
ID: 12372370
Tushar is my hero!

I thought i was doing a custom paging implementation, so I would  have never though that was incorrect.

As soon as I changed to "Allow  custom paging (Un checked)" my PageCount was corrected.


Whew! Thanks for all of your help!


0
 
LVL 18

Expert Comment

by:tusharashah
ID: 12372619
hehe.. thanks for that remarks..:)

Nice to have you going..

-tushar
0

Featured Post

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.

Question has a verified solution.

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

I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses
Course of the Month15 days, 9 hours left to enroll

850 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