Solved

paging help - urgent!!

Posted on 2004-10-20
21
288 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:jrmcdona
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
right before you bind your data to the datagrid put:

mydatagrid.CurrentPageIndex = 0

Aeros
0
 
LVL 17

Expert Comment

by:AerosSaga
Comment Utility
I think in C# it would be:

mydatagrid.CurrentPageIndex = 0;
0
 
LVL 18

Expert Comment

by:tusharashah
Comment Utility
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:jrmcdona
Comment Utility
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
Comment Utility
I thought you just said you weren't using paging????
0
 
LVL 17

Expert Comment

by:AerosSaga
Comment Utility
oh sorry diregard post was for another question.
0
 
LVL 17

Expert Comment

by:AerosSaga
Comment Utility
let me post my code for you.
0
 
LVL 17

Expert Comment

by:AerosSaga
Comment Utility
<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
Comment Utility
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
Comment Utility
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
Comment Utility
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 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
hehe.. thanks for that remarks..:)

Nice to have you going..

-tushar
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
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 …
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

743 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now