How to display Gridview Paging on Page Load when nothing is selected and on button click c#, asp.net?

Hi ,

I need to display the data
1.  in the Gridview on page load and
2. Depending upon the user selection and button click display the gridview
How to do the paging in the dropdownlist.

Below is my code:
<asp:DropDownList ID="ddlUserNames" runat="server" AppendDataBoundItems="true" CssClass="CriteriaField" DataSourceID="sdsUserNames" DataTextField="User_Name" Width="270px" >
						<asp:ListItem Text="Any" Value="0" />
			</asp:DropDownList>
<asp:DropDownList ID="ddlFeedbackTypes" runat="server" AppendDataBoundItems="true" CssClass="CriteriaField" DataSourceID="sdsFeedbackType" DataTextField="Type" DataValueField="ID"  Width="270px">
								<asp:ListItem Text="Any" Value="0" />
		  </asp:DropDownList>
      <asp:TextBox ID="txtLocation" runat="server" CssClass="CriteriaField" MaxLength="50" Width="150px" />
	   <asp:Button ID="ibSearch" OnClick="ibSearch_Click" 
                  runat="server"  Text="Search" />
 <asp:GridView ID="gvRecordList" runat="server" 
									 CellPadding="5" 
									 AllowPaging="true" 
									 AllowSorting="true"  
									 AutoGenerateColumns="false" 
									 CssClass="grid_view" 
									 DataKeyNames="FeedbackID"
									 GridLines="None"
									 HeaderStyle-CssClass="grid_view" 
									 PageSize="10"
									 Width="100%" ondatabound ="gvRecordList_DataBound"
                                       >
									<RowStyle CssClass="grid_view" />
									<AlternatingRowStyle CssClass="alt-data-row"  />
                                    


                                   <%-- <-- CausesValidation="false"-->--%>
									<Columns>
										<asp:TemplateField HeaderStyle-Width="50px" HeaderText="<br />ID" HeaderStyle-Wrap="false" SortExpression="FeedbackID" ItemStyle-VerticalAlign="Top">
											<ItemTemplate>
												<asp:LinkButton ID="btnEdit" runat="server"   CommandName="Select" ForeColor="#3A1E95" Text='<%# Eval("FeedbackID") %>' Width="50px" />
											</ItemTemplate>
										</asp:TemplateField>
																
                                        <asp:TemplateField HeaderStyle-VerticalAlign="Bottom" HeaderStyle-Width="125px" ItemStyle-HorizontalAlign="Left" ItemStyle-VerticalAlign="Top" ItemStyle-Width="125px">
																													</HeaderTemplate>
											<ItemTemplate>
												<asp:Label ID="lblFBType" runat="server" Text='<%# Eval("FeedbackTypes") %>' />
												<br /><br />
												<asp:Label ID="lblFBInfoType" runat="server" Text='<%# Eval("UserName") %>' />

<asp:Label ID="lblFBInfoType" runat="server" Text='<%# Eval("Location") %>' />



											</ItemTemplate>
										</asp:TemplateField>
																				
																			</Columns>
									<EmptyDataTemplate>
										<div style="padding: 10px;">
											No Records Found </div></EmptyDataTemplate>
                                            <PagerTemplate>
                                          

										<asp:Table ID="tblPager" runat="server" CssClass="pager" CellPadding="10" CellSpacing="0" Width="100%">
											<asp:TableRow>
												<asp:TableCell HorizontalAlign="Center" VerticalAlign="Middle">
													<asp:Table ID="tblPagerButtons" runat="server" CellPadding="0" Width="250px">
														<asp:TableRow>
															<asp:TableCell Width="33%">
																&nbsp;
															</asp:TableCell>
															<asp:TableCell HorizontalAlign="Left" VerticalAlign="Middle">
																<asp:ImageButton ID="imgFirst" runat="server" CommandArgument="First" ImageUrl="~/styles/img/first.png" OnCommand="Paginate"  ToolTip="Go To First Page" Width="16px" />
															</asp:TableCell>
															<asp:TableCell HorizontalAlign="Left" VerticalAlign="Middle">
																<asp:ImageButton ID="imgPrevious" runat="server" CommandArgument="Prev" ImageUrl="~/styles/img/previous.png" OnCommand="Paginate"  ToolTip="Go To Previous Page" Width="16px" />
															</asp:TableCell>
															<asp:TableCell HorizontalAlign="Right" VerticalAlign="Middle">
																&nbsp;&nbsp;&nbsp;Page&nbsp;&nbsp;
															</asp:TableCell>
															<asp:TableCell HorizontalAlign="Center" VerticalAlign="Middle">
																<asp:DropDownList ID="ddlPages" runat="server" onselectedindexchanged="ddlPages_SelectedIndexChanged" AutoPostBack="True" CssClass="lblField"  EnableViewState="true"  />
															</asp:TableCell>
															<asp:TableCell HorizontalAlign="Left" VerticalAlign="Middle">
																&nbsp;&nbsp;of&nbsp;<asp:Label ID="lblPageCount" runat="server" />&nbsp;&nbsp;&nbsp;
															</asp:TableCell>
															<asp:TableCell HorizontalAlign="Left" VerticalAlign="Middle">
																<asp:ImageButton ID="imgNext" runat="server" CommandArgument="Next" ImageUrl="~/styles/img/next.png" OnCommand="Paginate" ToolTip="Go To Next Page" Width="16px" />
															</asp:TableCell>
															<asp:TableCell HorizontalAlign="Left" VerticalAlign="Middle">
																<asp:ImageButton ID="imgLast" runat="server" CommandArgument="Last" ImageUrl="~/styles/img/last.png" OnCommand="Paginate" ToolTip="Go To Last Page" Width="16px" />
															</asp:TableCell>
															<asp:TableCell Width="33%">
																&nbsp;
															</asp:TableCell>
														</asp:TableRow>
													</asp:Table>
												</asp:TableCell></asp:TableRow><asp:TableRow>
												<asp:TableCell HorizontalAlign="Center" VerticalAlign ="Middle">
													<asp:Label ID="lblRecordCount" runat="server" Text="" />
												</asp:TableCell></asp:TableRow></asp:Table>
                                                </PagerTemplate>
                                                <PagerSettings Position="Bottom"   />
                                              
								</asp:GridView>


  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            FillGridView();
        }
    }

    protected void FillGridView()
    {
        DataTable dr = SearchFeedback();
        gvRecordList.DataSource = dr;
        gvRecordList.DataBind();
    }

    public DataTable SearchFeedback()
    {

        // Create a new Db Connection object using connection string
        SqlConnection objConnect = new SqlConnection(connectionString);

        // create new Command using stored proc name and Connection
        SqlCommand cmdNext = new SqlCommand("usp_GetResultSet", objConnect);
        cmdNext.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmdNext);


        try
        {
            // Open connection to the database
            objConnect.Open();

            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;

        }
        catch (Exception objErr)
        {
            throw (objErr);
        }
    }

    protected void gvRecordList_DataBound(Object sender, EventArgs e)
    {

        // Retrieve the pager row.
        GridViewRow pagerRow = gvRecordList.BottomPagerRow;

        // Retrieve the DropDownList and Label controls from the row.
        DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("ddlPages");
        Label pageLabel = (Label)pagerRow.Cells[0].FindControl("lblPageCount");

        if (pageList != null)
        {

            // Create the values for the DropDownList control based on 
            // the  total number of pages required to display the data
            // source.
            for (int i = 0; i < gvRecordList.PageCount; i++)
            {

                // Create a ListItem object to represent a page.
                int pageNumber = i + 1;
                ListItem item = new ListItem(pageNumber.ToString());

                // If the ListItem object matches the currently selected
                // page, flag the ListItem object as being selected. Because
                // the DropDownList control is recreated each time the pager
                // row gets created, this will persist the selected item in
                // the DropDownList control.   
                if (i == gvRecordList.PageIndex)
                {
                    item.Selected = true;
                }

                // Add the ListItem object to the Items collection of the 
                // DropDownList.
                pageList.Items.Add(item);

            }

        }

        if (pageLabel != null)
        {

            // Calculate the current page number.
            int currentPage = gvRecordList.PageIndex + 1;

            // Update the Label control with the current page information.
            //pageLabel.Text = "Page " + currentPage.ToString() +
            //  " of " + gvRecordList.PageCount.ToString();

        }

    }
    
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        //Retrieve the pager row.
        GridViewRow pagerRow = gvRecordList.BottomPagerRow;
        if ((pagerRow != null))
        {
            //Retrieve the PageDropDownList Dropfrom the bottom pager row.
            DropDownList ddlPages = (DropDownList)pagerRow.Cells[0].FindControl("ddlPages");
            //Set the PageIndex property to display that page selected by the user.
            gvRecordList.PageIndex = Convert.ToInt32(ddlPages.SelectedIndex);
            FillGridView();       
        }
    }

    protected void Paginate(object sender, CommandEventArgs e)
    {
        ImageButton btnCommand = (ImageButton)sender;
        var _with18 = gvRecordList;
        switch (btnCommand.CommandArgument)
        {
            case "First":
                if (_with18.PageIndex > 0)
                {
                    _with18.PageIndex = 0;
                }
                break;
            case "Prev":
                if (_with18.PageIndex > 0)
                {
                    _with18.PageIndex = (_with18.PageIndex - 1);
                }
                break;
            case "Next":
                if (_with18.PageIndex < (_with18.PageCount - 1))
                {
                    _with18.PageIndex = (_with18.PageIndex + 1);
                }
                break;
            case "Last":
                if (_with18.PageIndex < (_with18.PageCount - 1))
                {
                    _with18.PageIndex = _with18.PageCount - 1;
                }
                break;
        }

        FillGridView();
        
    }

    protected void ibSearch_Click(object sender, EventArgs e)
    {
        gvRecordList.Controls.Clear();
        gvRecordList.PageIndex = 0;
        string strLocation = "";
        string strUserName = "";
        int intFeedbackTypeID = 0;
       
              if (Request.Form["txtLocation"] != null)
        {
            strLocation = Request.Form["txtLocation"];
        }//

        if (string.IsNullOrEmpty(strLocation))
        {
            strLocation = null;
        }

        
        if (Request.Form["ddlUserNames"] != "0")
        {
            strBankerName = Request.Form["ddlUserrNames"];
        }
        else
        {
            strUserName = null;
        }
       
        //get FFAgent name
        //Feedback Type
        if (!string.IsNullOrEmpty(ddlFeedbackTypes.SelectedValue))
        {
            intFeedbackTypeID = Convert.ToInt32(ddlFeedbackTypes.SelectedValue);
            
        }
       
        
        {
            FillDataGrid( strLocation,  strUserName,
     intFeedbackTypeID);
        }


    }

    private void FillDataGrid(string strLocation, string strUserName,
     int intFeedbackTypeID)
    {
             

             DataTable dr =  SearchFeedback(strLocation, strUserName, intFeedbackTypeID);


        gvRecordList.DataSource = dr;
        gvRecordList.DataBind();
    }

    public DataTable SearchFeedback(string strLocation,
        string struserName,
        int intFeedbackTypeID)
    {

        // Create a new Db Connection object using connection string
        SqlConnection objConnect = new SqlConnection(connectionString);

        // create new Command using stored proc name and Connection
        SqlCommand cmdNext = new SqlCommand("usp_GetResultSetByParameters", objConnect);
        cmdNext.CommandType = CommandType.StoredProcedure;
        cmdNext.Parameters.Add(new SqlParameter("@Location", SqlDbType.VarChar, 50));
             cmdNext.Parameters.Add(new SqlParameter("@feedback_type_id", SqlDbType.Int));
               cmdNext.Parameters.Add(new SqlParameter("@user_name", SqlDbType.NVarChar, 100));

        cmdNext.Parameters["@Location"].Value = strLocation;
        if (intFeedbackTypeID > 0)
        {
            cmdNext.Parameters["@feedback_type_id"].Value = intFeedbackTypeID;
        }
        cmdNext.Parameters["@user_name"].Value = struserName;


        try
        {
            // Open connection to the database
            objConnect.Open();

            SqlDataAdapter da = new SqlDataAdapter(cmdNext);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;

        }
        catch (Exception objErr)
        {
            throw (objErr);
        }
    }

]

Open in new window

Saroj13Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sammySeltzerCommented:
Hi,

I just finished working on exactly what you are asking for.

Here is the code I used:

    Protected Sub PageDropDownList_SelectedIndexChanged(ByVal sender As [Object], ByVal e As EventArgs)

        ' Retrieve the pager row.
        Dim pagerRow As GridViewRow = gvCustomers.BottomPagerRow

        ' Retrieve the PageDropDownList DropDownList from the bottom pager row.
        Dim pageList As DropDownList = DirectCast(pagerRow.Cells(0).FindControl("PageDropDownList"), DropDownList)

        ' Set the PageIndex property to display that page selected by the user.
        gvCustomers.PageIndex = pageList.SelectedIndex
        Me.BindData()
    End Sub

    Protected Sub gvCustomers_DataBound(ByVal sender As [Object], ByVal e As EventArgs)

        ' Retrieve the pager row.
        Dim pagerRow As GridViewRow = gvCustomers.BottomPagerRow

        ' Retrieve the DropDownList and Label controls from the row.
        Dim pageList As DropDownList = DirectCast(pagerRow.Cells(0).FindControl("PageDropDownList"), DropDownList)
        Dim pageLabel As Label = DirectCast(pagerRow.Cells(0).FindControl("CurrentPageLabel"), Label)

        If pageList IsNot Nothing Then

            ' Create the values for the DropDownList control based on 
            ' the  total number of pages required to display the data
            ' source.
            For i As Integer = 0 To gvCustomers.PageCount - 1

                ' Create a ListItem object to represent a page.
                Dim pageNumber As Integer = i + 1
                Dim item As New ListItem(pageNumber.ToString())

                ' If the ListItem object matches the currently selected
                ' page, flag the ListItem object as being selected. Because
                ' the DropDownList control is recreated each time the pager
                ' row gets created, this will persist the selected item in
                ' the DropDownList control.   
                If i = gvCustomers.PageIndex Then
                    item.Selected = True
                End If

                ' Add the ListItem object to the Items collection of the 
                ' DropDownList.

                pageList.Items.Add(item)

            Next
        End If

        If pageLabel IsNot Nothing Then

            ' Calculate the current page number.
            Dim currentPage As Integer = gvCustomers.PageIndex + 1

            ' Update the Label control with the current page information.

            pageLabel.Text = "Page " + currentPage.ToString() + " of " + gvCustomers.PageCount.ToString()
        End If

    End Sub

Open in new window


Then on the markup, you add these:

        <pagertemplate>

          <table width="100%">                    
            <tr>                        
              <td style="width:70%">

                <asp:label id="MessageLabel"
                  forecolor="White"
                  text="Select a page:" 
                  runat="server"/>
                <asp:dropdownlist id="PageDropDownList"
                  autopostback="true"
                  onselectedindexchanged="PageDropDownList_SelectedIndexChanged" 
                  runat="server"/>

              </td>   
              <td style="width:70%; text-align:right">

                <asp:label id="CurrentPageLabel"
                  forecolor="White"
                  runat="server"/>

              </td>

            </tr>                    
          </table>
        </pagertemplate> 
            <AlternatingRowStyle BackColor="#dddddd" />  
            <PagerStyle BackColor="#444444" ForeColor="PeachPuff" Font-Bold="true" />  
            <HeaderStyle BackColor="#444444" Font-Italic="false" ForeColor="Snow" /> 

Open in new window


Add above code before <column>
.....

Also, please be sure to change to your gridview control id. Mine is gvCustomers.

The output will show you dropdown of pages.

You select say, page 3 and you get something like:

page 3 of ....

Hope this helps you.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Saroj13Author Commented:
My question is that: I want to display Gridview on Page Load including paging.
Second is I need to display the gridview on button click depending upon the users selection . I am using the same gridview. How to render gridview and paging..
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.