0

I just read some articles about paging gridview but I couldn't make it...

There is my full gridview's code:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" style="font-family: Verdana, Arial, Sans-Serif;" 

            CssClass="gridview" OnSorting="GridView_Sorting"
            DataKeyNames="id"
            AllowSorting ="True" BackColor="#CCCCCC"
            BorderStyle="Inset" BorderWidth="2px" BorderColor="GrayText"
            CellPadding="1"
            CellSpacing="5"
            HeaderStyle-HorizontalAlign="Center"
            OnRowDataBound="GridView1_RowDataBound"
            ForeColor = "Black" RowStyle-CssClass="gridview" 
            OnRowCommand="GridView1_RowCommand" AllowPaging="True" 
            OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5">            
            <AlternatingRowStyle BackColor="#CCCCCC" />
                <columns>

                    <asp:BoundField HeaderText="ID" DataField="id"  />
                    <asp:BoundField HeaderText="PRIORIDADE" DataField="prioridade" 
                        ItemStyle-HorizontalAlign="Center">
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>
                    <asp:BoundField  HeaderText="SITUAÇÃO"  DataField="situacao" ItemStyle-HorizontalAlign="Center" >
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="RESPONSAVEL" DataField="responsavel" HeaderStyle-Width="65px" ItemStyle-HorizontalAlign="Center">
                    <HeaderStyle Width="65px" />
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="DATA DE CADASTRO" DataField="dt_cadastro" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px" SortExpression="dt_cadastro"
                    ItemStyle-HorizontalAlign="Center" >
                    <HeaderStyle Width="60px" />
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="PREVISÃO DE TÉRMINO" DataField="previsao_termino" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px"
                    ItemStyle-HorizontalAlign="Center">
                    <HeaderStyle Width="60px" />
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="PROJETO" DataField="projeto"  ItemStyle-HorizontalAlign="Center">
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="FUNCIONALIDADE" DataField="funcionalidade" 
                        ItemStyle-HorizontalAlign="Center" >
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="CLUBE" DataField="clube"  
                        ItemStyle-HorizontalAlign="Center" >
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>

                    <asp:TemplateField HeaderStyle-Width="70px" HeaderText="VISUALIZAR" >
                        <ItemTemplate>
                            <asp:Button ID="Btn_Visualizar" runat="server" Text="VISUALIZAR" CssClass="Btn_Grid"  Font-Size="7pt" Font-Names="Verdana, Arial"  OnClick="Btn_Visualizar_Click"
                            CommandName="visualizar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />                            
                        </ItemTemplate>
                        <HeaderStyle Width="70px" />
                    </asp:TemplateField>
                    <asp:TemplateField HeaderStyle-Width="66px" HeaderText="ALTERAR">
                        <ItemTemplate>
                            <asp:Button ID="Btn_Alterar" runat="server" Text="ALTERAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana, Arial"
                            CommandName="editar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
                        </ItemTemplate>
                        <HeaderStyle Width="66px" />
                    </asp:TemplateField>
                    <asp:TemplateField HeaderStyle-Width="66px" HeaderText="FEEDBACK">
                        <ItemTemplate>
                            <asp:Button ID="Btn_Feedback" runat="server" Text="ADICIONAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana,Arial"
                            CommandName="feedback" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
                        </ItemTemplate>
                        <HeaderStyle Width="66px" />
                    </asp:TemplateField>

                </columns>
            <EditRowStyle ForeColor="Black" CssClass="GridViewEditRow" />
            <FooterStyle BackColor="#CCCCCC" />
            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" BorderColor="White" BorderStyle="Solid" BorderWidth="1px" />
            <PagerSettings Mode="NumericFirstLast" FirstPageText="First" LastPageText="Last" PageButtonCount="5" />
            <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
            <RowStyle BackColor="White" />
            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
            </asp:GridView>    

CodeBehind:

public partial class TodosChamados : System.Web.UI.Page
  {
    BDUsuarios usr = new BDUsuarios();
    BDFuncionalidades func = new BDFuncionalidades();
    BDChamados ch = new BDChamados();

protected void Page_Load(object sender, EventArgs e)
  {
    if (!IsPostBack)
       {
          GridView1.DataSource = ch.BuscaTodosChamados();
          GridView1.DataBind();
        }
  }

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[1].Text == "ALTA")
            {
                e.Row.Cells[1].BackColor = System.Drawing.Color.Red;
                e.Row.ControlStyle.Font.Bold = true;
            }
        }
        if (e.Row.Cells[0].Visible = e.Row.RowType == DataControlRowType.Pager)
        {
            e.Row.Cells[0].Visible = false;
        }
    }

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
 {
    if (e.CommandName != "Sort")
       {
          if (e.CommandName == "visualizar")
                {
                 Session["id"] = GridView1.Rows[Convert.ToInt32(e.CommandArgument.ToString())].Cells[0].Text;
                    Session["editar"] = null;
                }
                else if (e.CommandName == "editar")
                {
                    Session["id"] = GridView1.Rows[Convert.ToInt32(e.CommandArgument.ToString())].Cells[0].Text; //Grava o ID do chamado da linha correspondente.
                    Session["editar"] = 1; // 1 - Editar   2 - Não Editar .
                }

                else if (e.CommandName == "feedback")
                {
                    Session["id"] = GridView1.Rows[Convert.ToInt32(e.CommandArgument.ToString())].Cells[0].Text; //Grava o ID do chamado da linha correspondente.                
                    Response.Redirect("~/Adm/Feedback.aspx");
                }
                Response.Redirect("~/Adm/DetalhesChamado.aspx");
            }
        }

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
  {
      GridView1.PageIndex = e.NewPageIndex;
      GridView1.DataSource = ch.BuscaTodosChamados();
      GridView1.DataBind();
  }
Ghaleon
  • 1,186
  • 5
  • 28
  • 55
  • Have you ever used ASP.NET MVC? – The Muffin Man Feb 26 '13 at 19:14
  • No... I'm a "noob" when comes to Web programming ;s Sorry – Ghaleon Feb 26 '13 at 19:14
  • I'm just asking because I too put a lot of effort into Webforms before I learned MVC. All of this complex Gridview and Listview stuff is a waste of time. I suggest at least taking a look at MVC with the Razor view engine. – The Muffin Man Feb 26 '13 at 19:18
  • @Nick Yeah, my friend from work told me the same... Guess i'll start study MVC :s but now I need to finish this. It's almost done ;s Actually I love work with winforms, but it's not beeing so used now... ;\ I have to learn web ;P – Ghaleon Feb 26 '13 at 19:20
  • I like winforms style of development too, but that style doesn't work so great with the web. Webforms is a pain to debug and you don't have enough control of the output. I very much hated viewstate and page life cycle events Good luck to you. – The Muffin Man Feb 26 '13 at 19:33
  • @Nick Haha thanks, but as I finishe this, i'll convert to MVC ;s Everyone I talk about it tells me that MVC is much easier and better to work with ... Everyone can't be wrong ;P – Ghaleon Feb 26 '13 at 19:35

2 Answers2

1

Update 2

Now i hopefully have found the reason for your pager not being shown. You are making the first colum invisible, even for the pager-row in RowDataBound, but the pager is sitting in the first cell by default:

e.Row.Cells[0].Visible = false;

You have to check the correct RowType:

e.Row.Cells[0].Visible = e.Row.RowType == DataControlRowType.Pager;

or even better on the aspx markup:

<asp:BoundField HeaderText="ID" DataField="id" Visible="False" />

A silly question, have you set AllowPaging to true?

<asp:GridView Id="GridView1" runat="server" AllowPaging="True" >
    <PagerSettings Mode="NumericFirstLast" FirstPageText="First" LastPageText="Last" PageButtonCount="5" />
</asp:gridview>

GridView.AllowPaging Property

true if the paging feature is enabled; otherwise, false. The default is false.

You should also databind the GridView only if(!IsPostBack) when viwstate is enabled(default).

So wrap your databind code from Page_Load(i guess) into this check:

protected void Page_Load(Object sender, EventArgs e)
{
    if(!IsPostBack)
    {
         GridView1.DataSource = ch.BuscaTodosChamados();
         GridView1.DataBind();
    }
}

Otherwise events won't be triggered and changes will be overwritten when you reload data on postback.

Update According to your last edit:

I assume that your RowCommand is the reason for this issue. It is called before the PageIndexChanging event and it is triggered also when the page changes(if i remember correctly). So have a look at your Response.Redirect which happens when no if/else-if will catch it which seems to be the case.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName != "Sort")
    {
        if (e.CommandName == "visualizar")
        {
            // ..
        }
        else if (e.CommandName == "editar")
        {
           //..
        }

        else if (e.CommandName == "feedback")
        {
           //..
        }
        Response.Redirect("~/Adm/DetalhesChamado.aspx");
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Of course I did, still nothing happens, there's no numbers to page to the next... – Ghaleon Feb 26 '13 at 19:15
  • @Ghaleon: But the event is triggered? Have you set a breakpoint there? When you you databind the `GridView`? You should do that only `if(!IsPostBack)`. – Tim Schmelter Feb 26 '13 at 19:18
  • No, its not triggered ;s I updated my question with my gridview's code. – Ghaleon Feb 26 '13 at 19:19
  • I'm doing this, and viewe state is as default(Inherit). Now I set `ViewStateMode: Enabled` but still the same. Nothing of pagging. I don't know if it matters, but, in `Designe View` I can see the numbers of the pagging, but when I debug it, there's nothing... – Ghaleon Feb 26 '13 at 19:24
  • As i've mentioned, ViewState is enabled by default. Are you using ASP.NET Ajax? Are you sure that there`s no client- or serverside exception? What are you doing in `Page_Init`/`Page_Load`? What is the datasource, how many records does it contain? – Tim Schmelter Feb 26 '13 at 19:28
  • @Ghaleon: I'm fairly sure that `RowCommand` is triggered also on `PageIndexChaning`. Your first condition will be true and at the end you are doing a `Response.Redirect`. Can this be the reason? Eddited my answer accordingl.y – Tim Schmelter Feb 26 '13 at 19:44
  • But it will goes to the RowCommand only if I click on a button or something, the `numbers` of the paging, wasn't supposed to appear when I load the page ? – Ghaleon Feb 26 '13 at 19:46
  • @Ghaleon: What is the exact issue? Do you have no numbers or does the page not change when you click on the pager? Does it postback at all? – Tim Schmelter Feb 26 '13 at 19:50
  • My `GridView` is filled normally from the `codebehind`, but there's no numbers to change to other page, you know ? Just a normal `GridView` without paging option ;s – Ghaleon Feb 26 '13 at 19:52
  • YES!! I also commented the `RowCommand` and `RowDataBound` without these 2 it worked perfect... Removing `RowDataBound` the numbers shows perfect, and removing the `RowCOmmand` it goes to the next page perfect !! I just don't know how keep doing what i'm doing and also page it normally. I cant set the invisible on HTML, because then i'll not be able to capture it's value. :S – Ghaleon Feb 26 '13 at 20:08
  • @Ghaleon: Have you seen my last edit? You can decide whether you want to hide it in RowDataBound or on the aspx markup. Both will work. – Tim Schmelter Feb 26 '13 at 20:10
  • I updated my question with the new `RowDataBound`code. The numbers still not showing. And What may I do to solve the problem of ´RowCommand` ? – Ghaleon Feb 26 '13 at 20:12
  • @Ghaleon: Why have you not used my code? `e.Row.Cells[0].Visible = e.Row.RowType == DataControlRowType.Pager;`. What problem do you have with `RowCommand`? Why are you redirecting to another page always? Have you seen the part of my answer targetting this issue? – Tim Schmelter Feb 26 '13 at 20:15
  • Your code was to add and condition `e.Row.Cells[0].Visible = e.Row.RowType == DataControlRowType.Pager;` wasn't it ? I added it ;s And it hides the ID column, but also hides the numbers. And to solve the problem in the `RowCommand` I just added another condition on the first `if (... && e.CommandName != "Page")`, and worked. – Ghaleon Feb 26 '13 at 20:17
  • @Ghaleon: If nothing works just move the id-column you want to hide to the end and hide it by setting `Visible=False` on the aspx markup(or in codebehind if you prefer that). – Tim Schmelter Feb 26 '13 at 20:19
  • I'm trying, but now, i get error something like `index is out of range`;s There's 11 columns, If I set the invisibility to any index but 0, the error happens ;s e.g: `e.Cells[10].Visible = false` would you know why ? Thanks Tim ! – Ghaleon Feb 26 '13 at 20:28
  • @Ghaleon: Why don't you set the visibility on the aspx markup? That would be much easier and also allows to change it without recompiling. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datacontrolfield.visible.aspx – Tim Schmelter Feb 26 '13 at 20:32
  • I tried... The coulumn that i'm hiding is the ID column, and I'm assigning it's value to a `Session`. If i hide if from the markup, the value will always be `""`, but if I hide it from the codeBehind, I'm able to get it's value. I don't know why, but it is like this ;\. Have a solution to work around it ? – Ghaleon Feb 26 '13 at 20:35
  • @Ghaleon: I'm using the same functionality in one of my projects and it works without problems to hide the id-column and access the value in codebehind. Where do you assign the value, where are you trying to read it and why do you need the session at all when viewstate is enabled anyway? – Tim Schmelter Feb 26 '13 at 20:37
  • I read a lot about how pass a value to another page, My "boss" don't want to use query string, I tried but failed using ViewState, so the only thing I could do is passing it using `Session` =\ i'm a total failure! – Ghaleon Feb 26 '13 at 20:41
  • I see, you want to read it in `RowCommand`. You're using `BoundFields`, therefore the cell-text is empty when the column is invisible. There are two ways around this. The first is using `GridView1.DataKeys[index].Value`. Otherwise you can convert your boundfield to a template field and use `FindControl` to get the value of the `Label` bound to `ID`. Then the `Label.Text` is stored in ViewState even if it is invisible. – Tim Schmelter Feb 26 '13 at 20:46
  • `DataKeys` is a parameter, it does not accept nothing like `DataKeys(SomeValue)` its like ReadOnly Idk... So there's no `DataKeys(SomeValue).Value` ;s I'll try the second option – Ghaleon Feb 26 '13 at 20:49
  • @Ghaleon: Edited my last comment, mistakenly used VB.NET since i was programming in VB ;) Here is a question where you can read how to get the row-index in `RowCommand`: http://stackoverflow.com/q/2818203/284240 Btw, i would replace the `BoundField` with a `TemplateField` and add a `Label` instead, but that's a matter of taste. – Tim Schmelter Feb 26 '13 at 20:50
  • Thanks Tim, i'll try ! You always saving me here ;x Really thank you ! I'll try it right now. – Ghaleon Feb 26 '13 at 20:56
0

You must specify the event for OnPageIndexChanging in your .aspx. It should be:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
        OnPageIndexChanging = "GridView1_PageIndexChanging" 
        AutoGenerateColumns="False" DataKeyNames="LastName,FirstName"
        EnablePersistedSelection="True" SelectedRowStyle-BackColor="Yellow" 
        DataSourceID="SqlDataSource1" AllowSorting="True">

You might be having the same problem here

UPDATE

Make sure that the data that's being bound to the GridView is more that 5 since PageSize="5". If the number of rows is less than 5, then the pager will not be shown.

Community
  • 1
  • 1
Andy Refuerzo
  • 3,312
  • 1
  • 31
  • 38
  • Updated my answer, how many rows are returned by `ch.BuscaTodosChamados();`? – Andy Refuerzo Feb 26 '13 at 19:29
  • It's returning all of them... But shows the quantity that I set by PageSize = NumberOfRowsToShow. Right ? But there's nothing of pagging... ;s I updated my question with my full CodeBehind – Ghaleon Feb 26 '13 at 19:30
  • how many records is 'all of them'? You may also want to try to remove any css styling in the mean time just to be sure that nothing is being hidden. – Andy Refuerzo Feb 26 '13 at 19:39
  • I have 15 records/rows on my database's table. I know its not much, i just meant that it was retrieve every single record that's on the table, just like it was supposed to be. I'll try remove all the CSS of my gridview. – Ghaleon Feb 26 '13 at 19:41
  • still the same.. Even Without CSS ;s – Ghaleon Feb 26 '13 at 20:03