GridView Control in ASP.NET: Part 2

Please you do read earlier parts of this article for complete understanding in GridView.

Part - 1

Paging GridView

If we have large amount of data in GridView then we need to display the rows in different pages. We can enable paging with the GridView control by enabling its AllowPaging property. We can also determine how many rows want to see in one page by setting the PageSize property. 

Grid1.gif

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style type
="text/css">

    </style>
</head>
<
body>
    <form id="form1" runat="server" >
    <div>
        <asp:GridView ID="GridView1" 
        runat="server" 
        DataSourceID="SqlDataSource1"
        AutoGenerateSelectButton="true" 
        PageSize="2" 
        AllowPaging
="true">

        <SelectedRowStyle 
        CssClass="mycss" 
        BackColor="#666699" 
        BorderColor="Red">
        </SelectedRowStyle>
 
        </asp:GridView
>

        <br />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString1 %>" 
            SelectCommand="SELECT * FROM MyTB">
        </asp:SqlDataSource>
        <br />
 
    </div>
    </form
>
</body>
</
html>

Paging with AJAX

The default behavior of the GridView control is to post back to the server each and every time we navigate to a new page of records. However, there is an alternative of AJAX (Asynchronous JavaScript and XML) when paging through records with the GridView control.

Grid2.gif

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Using Data Keys</title>
    <style type="text/css">

    </style
>
</head>
<
body>
        <form id="form1" runat="server" >
        <div>
        <div>
        <br />
        <br />
        <%= DateTime.Now.ToString("T"%>
        <br />
        <br />
        <b>This is without postback to server.</b>
        <br />
        <br />
        </div>
        <asp:GridView ID="GridView1" 
        runat="server" 
        DataSourceID="SqlDataSource1"
        PageSize="2" 
        AllowPaging="true" 
        PagerSettings-Mode="NextPreviousFirstLast"
        PagerSettings-Position="TopAndBottom"
        PagerStyle-HorizontalAlign="Left"
        EnableSortingAndPagingCallbacks="true" 
        Width="603px">
        </asp:GridView>
        <br />
        <br />
        <br />
        <b>This is with postback to server.</b>
        <br />
        <asp:GridView ID="GridView2" 
        runat="server" 
        DataSourceID="SqlDataSource1"
        PageSize="2" 
        AllowPaging="true"
        PagerSettings-Mode="NextPreviousFirstLast"
        PagerSettings-Position="TopAndBottom"
        PagerStyle-HorizontalAlign="Left"
        Width="603px">
        </asp:GridView>
        <br />
        <br />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString1 %>" 
            SelectCommand="SELECT * FROM MyTB">
        </asp:SqlDataSource>
        <br 
/>

    </div>
    </form
>
</body>
</
html>

In above example, I have used two GridView controls but first one is with AJAX and second one is without AJAX. I have also used some different navigation item in above example.

Using Pager Templates


By default, when paging is enabled, the GridView renders a list of page numbers at the bottom of the grid. We can modify the user interface for paging through records by modifying the GridView control's PagerSettings property. The PagerSettings class supports the following properties:

  • FirstPageImageUrl Enables us to display an image for the first page link.
     
  • FirstPageText Enables us to specify the text for the first page link.
     
  • LastPageImageUrl Enables us to display an image for the last page link.
     
  • LastPageText Enables us to specify the text for the last page link.
     
  • Mode Enables us to select a display mode for the pager user interface. Possible values are NextPrevious, NextPreviousFirstLast, Numeric, and NumericFirstLast.
     
  • NextPageImageUrl Enables us to display an image for the next page link.
     
  • NextPageText Enables us to specify the text for the next page link.
     
  • PageButtonCount Enables us to specify the number of page number links to display.
     
  • Position Enables us to specify the position of the paging user interface. Possible values are Bottom, Top, TopAndBottom.
     
  • PreviousPageImageUrl Enables us to display an image for the previous page link.
     
  • PreviousPageText Enables us to specify the text for the previous page link.
     
  • Visible Enables us to hide the paging user interface.

The PageButtonCount requires more explanation. Imagine that we are displaying the contents of a database table that contains 3 billion records and we are displaying two records per page. In that case, we would need to render an overwhelming number of page numbers. The PageButtonCount property enables we to limit the number of page numbers displayed at once. When PageButtonCount has a value less than the number of page numbers, the GridView renders ellipsis, which enables a user to move between ranges of page numbers.

The GridView control includes a PagerTemplate, which enables us to completely customize the appearance of the paging user interface. For example, the PagerTemplate also includes two LinkButton controls, which represent a Previous and Next link. 

Grid3.gif

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    Protected Sub paging_DataBound(ByVal sender As ObjectByVal e As EventArgs)
        Dim menuPager As Menu = CType(GridView1.BottomPagerRow.FindControl("menuPager"),Menu)
        For i As Integer = 0 To GridView1.PageCount - 1
            Dim item As New MenuItem()
            item.Text = String.Format("[{0}]", i + 1)
            item.Value = i.ToString()
            If GridView1.PageIndex = i Then
                item.Selected = True
            End If
            menuPager.Items.Add(item)
        Next
    End Sub

    Protected Sub menuPager_MenuItemClick(ByVal sender As ObjectByVal e As MenuEventArgs)
        GridView1.PageIndex = Int32.Parse(e.Item.Value)
    End Sub
</
script>

<html xmlns="http://www.w3.org/1999/xhtml">
<
head id="Head1" runat="server">
    <title></title>
    <style type="text/css">
    .menu td
        {
            padding:5px 0px;
        }
    .selectedPage a
        {
            font-weight:bold;
            color:red;
        }

    </style>
</
head>
<
body>
    <form id="form1" runat="server">
    <div>

    <asp:GridView
        id="GridView1"
        DataSourceID="SqlDataSource1"
        AllowPaging="true"
        PageSize="2"
        Runat="server" 
        OnDataBound="paging_DataBound" Width="622px">
        <PagerTemplate>
        <table>
        <tr><td>
        <asp:LinkButton
            id="lnkPrevious"
            Text="&lt; Prev"
            CommandName="Page"
            CommandArgument="Prev"
            ToolTip="Previous Page"
            Runat="server" />
        </td><td>
        <asp:Menu
            id="menuPager"
            Orientation="Vertical"
            OnMenuItemClick="menuPager_MenuItemClick"
            StaticSelectedStyle-CssClass="selectedPage"
            CssClass="menu"
            Runat="server" />
        </td><td>
        <asp:LinkButton
            id="lnkNext"
            Text="Next &gt;"
            CommandName="Page"
            CommandArgument="Next"
            ToolTip="Next Page"
            Runat="server" />
        </td></tr>
        </table>
        </PagerTemplate>
    </asp:GridView>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString1 %>" 
            SelectCommand="SELECT * FROM MyTB">
    </asp:SqlDataSource>

    </div>
    </form>
</
body>

</html>

Editing Data

The GridView control also enables us to edit database data. The amazing thing is that we can use the GridView to edit the content of a database table row without writing a single line of code. Here is an example which illustrates how we can update and delete record in the database table using GridView only.

Grid4.gif

<%
@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<
head id="Head1" runat="server">
    <title></title>
    <style type="text/css">

    </style>
</
head>
<
body>
    <form id="form1" runat="server" >
    <div>
    <br /><br /><br />
        <asp:GridView 
        ID="GridView1" 
        runat="server" 
        DataSourceID="SqlDataSource1"
        PageSize="2" 
        AutoGenerateEditButton="true"
        AutoGenerateDeleteButton="true"
        DataKeyNames="ID"
        AllowPaging="true">

        <SelectedRowStyle 
        CssClass="mycss" 
        BackColor="#666699" 
        BorderColor="Red">
        </SelectedRowStyle>

        </asp:GridView>

        <br />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString1 %>" 
            SelectCommand="SELECT * FROM MyTB" 
            UpdateCommand="UPDATE MyTB SET Name=@Name, Address=@Address WHERE ID=@ID"
            DeleteCommand="DELETE MyTB WHERE ID=@ID">
        </asp:SqlDataSource>
        <br />

    </div>
    </form>
</
body>
</
html>

Notice that the GridView control has both its AutoGenerateEditButton and AutoGenerateDeleteButton properties enabled. When these properties are enabled, Edit and Delete links are automatically rendered next to each row in the GridView.

Displaying Empty Data/Searching for Data

The GridView includes two properties that enable you to display content when no results are returned from the GridView control's data source. You can use either the EmptyDataText property or the EmptyDataTemplate property to handle empty data. The example given below contains a search form. If we enter a search string that does not match the start of any name, then the contents of the EmptyDataText property will be displayed.

Grid5.gif

<%
@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    Protected Sub btnSubmit_Click(ByVal sender As ObjectByVal e As System.EventArgs)
        GridView1.Visible = True
    End Sub
</
script>

<html xmlns="http://www.w3.org/1999/xhtml">
<
head id="Head1" runat="server">
    <title></title>
    <style type="text/css">

    </style>
</
head>
<
body>
    <form id="form1" runat="server" >
    <div>
    <br /><br /><br />
       <b>Enter your name to search.</b>
       <br />
        <asp:TextBox
        id="txtName"
        Runat="server" />

        <asp:Button
        id="btnSubmit"
        Text="Search"
        OnClick="btnSubmit_Click"
        Runat="server" />
        <hr />

        <asp:GridView
        id="GridView1"
        DataSourceID="SqlDataSource1"
        EmptyDataText="<img src='sad.GIF'/> No Matching Data!"
        Visible="false"
        Runat="server" />

        <br />
        <asp:SqlDataSource
        id="SqlDataSource1"
        ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString1 %>"
        SelectCommand="SELECT iD, Name, Address, Contact FROM MyTB WHERE Name LIKE +'%'+ @Name+'%'"
        Runat="server">
        <SelectParameters>
        <asp:ControlParameter
            Name="Name"
            ControlID="txtName"
            PropertyName="Text" />
        </SelectParameters>
        </asp:SqlDataSource>
        <br />

    </div>
    </form>
</
body>
</
html>

Formatted GridView Look

The GridView control includes a rich set of formatting properties that you can use to modify its appearance. I recommend that you don't use most of these properties because using these properties results in bloated pages. Instead, I recommend that you use Cascading Style Sheets to format the GridView control.

The GridView control includes a CssClass property. The control also exposes several Style objects that include the CssClass property:

  • AlternatingRowStyle Enables you to format every other row.  
     
  • FooterStyle Enables you to format the footer row.
     
  • HeaderStyle Enables you to format the header row.
     
  • PagerStyle Enables you to format the pager row.
     
  • RowStyle Enables you to format each row.
     
  • SelectedRowStyle Enables you to format the selected row.

    Grid6.gif
     
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<
head id="Head1" runat="server">
    <title></title>
    <style type="text/css">

    </style>
</
head>
<
body>
    <form id="form1" runat="server" >
    <div>
    <br /><br /><br />
        <asp:GridView 
        ID="GridView1" 
        runat="server" 
        DataSourceID="SqlDataSource1"
        PageSize="2" 
        AllowPaging="True" BackColor="#DEBA84" BorderColor="#DEBA84" 
            BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" 
            Width="683px">
            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
            <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#FFF1D4" />
            <SortedAscendingHeaderStyle BackColor="#B95C30" />
            <SortedDescendingCellStyle BackColor="#F1E5CE" />
            <SortedDescendingHeaderStyle BackColor="#93451F" />
        </asp:GridView>

        <br />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString1 %>" 
            SelectCommand="SELECT * FROM MyTB" 
            UpdateCommand="UPDATE MyTB SET Name=@Name, Address=@Address WHERE ID=@ID"
            DeleteCommand="DELETE MyTB WHERE ID=@ID">
        </asp:SqlDataSource>
        <br />

    </div>
    </form>
</
body>
</
html>

Note: Continue in Next Part.

HAVE A GREAT CODING!

Up Next
    Ebook Download
    View all
    Learn
    View all