Microsoft.NET

……………………………………………….Expertise in .NET Technologies

GridView Control in ASP.NET – Part 1

Posted by Ravi Varma Thumati on January 16, 2012

The GridView Control

The GridView is an extremely flexible grid control that displays a multicolumn table. Each record in your data source becomes a separate row. Each field in the record becomes a separate column.

The GridViewcontrol supports the following features:

  • Binding to data source controls, such as SqlDataSource.
  • Built-in sort capabilities.
  • Built-in update and delete capabilities.
  • Built-in paging capabilities.
  • Built-in row selection capabilities.
  • Programmatic access to the GridView object model to dynamically set properties, handle events, and so on.
  • Multiple key fields.
  • Multiple data fields for the hyperlink columns.
  • Customizable appearance through themes and styles.

Automatically Generating Columns

The GridView provides a DataSource property for the data object you want to display, much like the list controls, Once you’ve set the DataSource property, you call the DataBind() method to perform the data binding and display each record in the GridView. However, the GridView doesn’t provide properties, such as DataTextField and DataValueField that allow you to choose what column you want to display. That’s because the GridView automatically generates a column for every field, as long as the AutoGenerateColumns property is True.

<asp:GridView ID=”GridView1″ runat=”server” />

Once you’ve added this GridView tag to your page, you can fill it with data. Here’s an example that performs a query using the ADO.NET objects and binds the retrieved DataSet:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

‘ Define the ADO.NET objects.

         Dim connectionString As String = WebConfigurationManager.ConnectionStrings(“Northwind”).ConnectionString

         Dim selectSQL As String = “SELECT ProductID, ProductName, UnitPrice FROM Products”

         Dim con As New SqlConnection(connectionString)

         Dim cmd As New SqlCommand(selectSQL, con)

         Dim adapter As New SqlDataAdapter(cmd)

         ‘ Fill the DataSet

         Dim ds As New DataSet ()

         adapter.Fill(ds, “Products”)

         ‘ Perform the binding.

         GridView1.DataSource = ds

         GridView1.DataBind()

End Sub

C#

protected void Page_Load(object sender, EventArgs e)

{

         // Define the ADO.NET objects.

         string connectionString = WebConfigurationManager.ConnectionStrings(“Northwind”).ConnectionString;

         string selectSQL = “SELECT ProductID, ProductName, UnitPrice FROM Products”;

         SqlConnection con = new SqlConnection(connectionString);

         SqlCommand cmd = new SqlCommand(selectSQL, con);

         SqlDataAdapter adapter = new SqlDataAdapter(cmd);

         // Fill the DataSet

         DataSet ds = new DataSet();

         adapter.Fill(ds, “Products”);

         // Perform the binding.

         GridView1.DataSource = ds;

         GridView1.DataBind();

}

Of course, you don’t need to write this data access code by hand, you can use the SqlDataSource control to define your query. You can then link that query directly to your data control, and ASP.NET will take care of theentire data binding process.

Here’s how you would define a SqlDataSource to perform the query shown in the previous example:

<asp:SqlDataSource ID=”sourceProducts” runat=”server”

ConnectionString=”<%$ ConnectionStrings:Northwind %>”

SelectCommand=”SELECT ProductID, ProductName, UnitPrice FROM Products” />

Next, set the GridView.DataSourceID property to link the data source to your grid:

<asp:GridView ID=”GridView1″ runat=”server” DataSourceID=”sourceProducts” />

Defining Columns

By default, the GridView.AutoGenerateColumns property is True, and the GridView creates a column for each field. This automatic column generation is good for creating quick test pages, but it doesn’t give you the flexibility you’ll usually want. For example, what if you want to hide columns, change their order, or configure some aspect of their display, such as the formatting or heading text? In all these cases, you need to set AutoGenerateColumns to False and define the columns in the <Columns> section of the GridView control tag.

Each column in the GridView control is represented by a DataControlField object. By default, the AutoGenerateColumns property is set to true, which creates an AutoGeneratedField object for each field in the data source. Each field is then rendered as a column in the GridView control in the order that each field appears in the data source.

You can also manually control which column fields appear in the GridView control by setting the AutoGenerateColumns property to false and then defining your own column field collection. Different column field types determine the behavior of the columns in the control. The following table lists the different column field types that can be used.

Column field type Description
BoundField Displays the value of a field in a data source. This is the default column type of the GridView control.
ButtonField Displays a command button for each item in the GridView control. This enables you to create a column of custom button controls, such as the Add or the Remove button.
CheckBoxField Displays a check box for each item in the GridView control. This column field type is commonly used to display fields with a Boolean value.
CommandField Displays predefined command buttons to perform select, edit, or delete operations.
HyperLinkField Displays the value of a field in a data source as a hyperlink. This column field type enables you to bind a second field to the hyperlink’s URL.
ImageField Displays an image for each item in the GridView control.
TemplateField Displays user-defined content for each item in the GridView control according to a specified template. This column field type enables you to create a custom column field.

To define a column field collection declaratively, first add opening and closing <Columns> tags between the opening and closing tags of the GridView control. Next, list the column fields that you want to include between the opening and closing <Columns> tags. The columns specified are added to the Columns collection in the order listed. The Columns collection stores all the column fields in the control and enables you to programmatically manage the column fields in the GridView control.

Explicitly declared column fields can be displayed in combination with automatically generated column fields. When both are used, explicitly declared column fields are rendered first, followed by the automatically generated column fields.

Explicitly defining columns has several advantages:

  • You can easily fine-tune your column order, column headings, and other details by tweaking the properties of your column object.
  • You can hide columns you don’t want to show by removing the column tag. (Don’t overuse this technique, because it’s better to reduce the amount of data you’re retrieving if you don’t intend to display it.)
  • You’ll see your columns in the design environment (in Visual Studio). With automatically generated columns, the GridView simply shows a few generic placeholder columns.
  • You can add extra columns to the mix for selecting, editing, and more.

Binding to Data

The GridView control can be bound to a data source control (such as the SqlDataSource control or ObjectDataSource control) or to any data source collection that implements the System.Collections.IEnumerable interface, such as System.Data.DataView,  System.Collections.ArrayList,  System.Collections.Generic.List(Of T), or other collection types. Use one of the following methods to bind the GridView control to the appropriate data source type:

  • To bind to a data source control, set the DataSourceID property of the GridView control to the ID value of the data source control. The GridView control automatically binds to the specified data source control and can take advantage of the data source control’s capabilities to perform sorting, updating, deleting, and paging. This is the preferred method to bind to data.
  • To bind to a data source that implements the System.Collections.IEnumerable interface, programmatically set the DataSource property of the GridViewcontrol to the data source and then call the DataBind method. When using this method, the GridView control does not provide built-in sort, update, delete, and paging functionality. You need to provide this functionality by using the appropriate event.

Data Operations

The GridView control provides many built-in capabilities that allow the user to sort, update, delete, select, and page through items in the control. When theGridView control is bound to a data source control, the GridView control can take advantage of the data source control’s capabilities and provide automatic sort, update, and delete functionality.

Sorting allows the user to sort the items in the GridView control with respect to a specific column by clicking on the column’s header. To enable sorting, set theAllowSorting property to true.

The automatic updating, deleting, and selection functionalities are enabled when a button in a ButtonField or TemplateField column field, with a command name of “Edit”, “Delete”, and “Select”, respectively, is clicked. The GridView control can automatically add a CommandField column field with an Edit, Delete, or Select button if the AutoGenerateEditButton, AutoGenerateDeleteButton, or AutoGenerateSelectButton property is set to true, respectively.

Instead of displaying all the records in the data source at the same time, the GridView control can automatically break the records up into pages. To enable paging, set the AllowPaging property to true.

Customizing the User Interface

You can customize the appearance of the GridView control by setting the style properties for the different parts of the control. The following table lists the different style properties.

Style property

Description

AlternatingRowStyle The style settings for the alternating data rows in the GridView control. When this property is set, the data rows are displayed alternating between the RowStyle settings and the AlternatingRowStyle settings.
EditRowStyle The style settings for the row being edited in the GridView control.
EmptyDataRowStyle The style settings for the empty data row displayed in the GridView control when the data source does not contain any records.
FooterStyle The style settings for the footer row of the GridView control.
HeaderStyle The style settings for the header row of the GridView control.
PagerStyle The style settings for the pager row of the GridView control.
RowStyle The style settings for the data rows in the GridView control. When the AlternatingRowStyle property is also set, the data rows are displayed alternating between the RowStyle settings and the AlternatingRowStyle settings.
SelectedRowStyle The style settings for the selected row in the GridView control.
SortedAscendingCellStyle The style setting for the data column the data is sorted by in the GridView control. When this style is set, the style (for example, highlighted column) is applied to cells when the data is sorted in ascending order.
SortedAscendingHeaderStyle The style setting for the data column the data is sorted by in the GridView control. When this style is set, an arrow indicating the data is sorted ascending is placed on the header of the GridView control when the data is sorted in ascending order.
SortedDescendingCellStyle The style setting for the data column the data is sorted by in the GridView control. When this style is set, the style (for example, highlighted column) is applied to cells when the data is sorted in descending order.
SortedDescendingHeaderStyle The style setting for the data column the data is sorted by in the GridView control. When this style is set, an arrow pointing down is placed on the header of the GridView when the data is sorted in descending order.

You can also show or hide different parts of the control. The following table lists the properties that control which parts are shown or hidden.

Property Description
ShowFooter Shows or hides the footer section of the GridView control.
ShowHeader Shows or hides the header section of the GridView control.

Events

The GridView control provides several events that you can program against. This enables you to run a custom routine whenever an event occurs. The following table lists the events that are supported by the GridView control.

Event

Description

PageIndexChanged Occurs when one of the pager buttons is clicked, but after the GridView control handles the paging operation. This event is commonly used when you need to perform a task after the user navigates to a different page in the control.
PageIndexChanging Occurs when one of the pager buttons is clicked, but before the GridView control handles the paging operation. This event is often used to cancel the paging operation.
RowCancelingEdit Occurs when a row’s Cancel button is clicked, but before the GridView control exits edit mode. This event is often used to stop the canceling operation.
RowCommand Occurs when a button is clicked in the GridView control. This event is often used to perform a task when a button is clicked in the control.
RowCreated Occurs when a new row is created in the GridView control. This event is often used to modify the contents of a row when the row is created.
RowDataBound Occurs when a data row is bound to data in the GridView control. This event is often used to modify the contents of a row when the row is bound to data.
RowDeleted Occurs when a row’s Delete button is clicked, but after the GridView control deletes the record from the data source. This event is often used to check the results of the delete operation.
RowDeleting Occurs when a row’s Delete button is clicked, but before the GridView control deletes the record from the data source. This event is often used to cancel the deleting operation.
RowEditing Occurs when a row’s Edit button is clicked, but before the GridView control enters edit mode. This event is often used to cancel the editing operation.
RowUpdated Occurs when a row’s Update button is clicked, but after the GridView control updates the row. This event is often used to check the results of the update operation.
RowUpdating Occurs when a row’s Update button is clicked, but before the GridView control updates the row. This event is often used to cancel the updating operation.
SelectedIndexChanged Occurs when a row’s Select button is clicked, but after the GridView control handles the select operation. This event is often used to perform a task after a row is selected in the control.
SelectedIndexChanging Occurs when a row’s Select button is clicked, but before the GridView control handles the select operation. This event is often used to cancel the selection operation.
Sorted Occurs when the hyperlink to sort a column is clicked, but after the GridView control handles the sort operation. This event is commonly used to perform a task after the user clicks a hyperlink to sort a column.
Sorting Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation. This event is often used to cancel the sorting operation or to perform a custom sorting routine.

Declarative Syntax

<asp:GridView

    AccessKey=”string”

    AllowPaging=”True|False”

    AllowSorting=”True|False”

    AutoGenerateColumns=”True|False”

    AutoGenerateDeleteButton=”True|False”

    AutoGenerateEditButton=”True|False”

    AutoGenerateSelectButton=”True|False”

    BackColor=”color name|#dddddd”

    BackImageUrl=”uri”

    BorderColor=”color name|#dddddd”

    BorderStyle=”NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|Inset|Outset”

    BorderWidth=”size”

    Caption=”string”

    CaptionAlign=”NotSet|Top|Bottom|Left|Right”

    CellPadding=”integer”

    CellSpacing=”integer”

    CssClass=”string”

    DataKeyNames=”string”

    DataMember=”string”

    DataSource=”string”

    DataSourceID=”string”

    EditIndex=”integer”

    EmptyDataText=”string”

    Enabled=”True|False”

    EnableSortingAndPagingCallbacks=”True|False”

    EnableTheming=”True|False”

    EnableViewState=”True|False”

    Font-Bold=”True|False”

    Font-Italic=”True|False”

    Font-Names=”string”

    Font-Overline=”True|False”

    Font-Size=”string|Smaller|Larger|XX-Small|X-Small|Small|Medium|Large|X-Large|XX-Large”

    Font-Strikeout=”True|False”

    Font-Underline=”True|False”

    ForeColor=”color name|#dddddd”

    GridLines=”None|Horizontal|Vertical|Both”

    Height=”size”

    HorizontalAlign=”NotSet|Left|Center|Right|Justify”

    ID=”string”

    OnDataBinding=”DataBinding event handler”

    OnDataBound=”DataBound event handler”

    OnDisposed=”Disposed event handler”

    OnInit=”Init event handler”

    OnLoad=”Load event handler”

    OnPageIndexChanged=”PageIndexChanged event handler”

    OnPageIndexChanging=”PageIndexChanging event handler”

    OnPreRender=”PreRender event handler”

    OnRowCancelingEdit=”RowCancelingEdit event handler”

    OnRowCommand=”RowCommand event handler”

    OnRowCreated=”RowCreated event handler”

    OnRowDataBound=”RowDataBound event handler”

    OnRowDeleted=”RowDeleted event handler”

    OnRowDeleting=”RowDeleting event handler”

    OnRowEditing=”RowEditing event handler”

    OnRowUpdated=”RowUpdated event handler”

    OnRowUpdating=”RowUpdating event handler”

    OnSelectedIndexChanged=”SelectedIndexChanged event handler”

    OnSelectedIndexChanging=”SelectedIndexChanging event handler”

    OnSorted=”Sorted event handler”

    OnSorting=”Sorting event handler”

    OnUnload=”Unload event handler”

    PageIndex=”integer”

    PagerSettings-FirstPageImageUrl=”uri”

    PagerSettings-FirstPageText=”string”

    PagerSettings-LastPageImageUrl=”uri”

    PagerSettings-LastPageText=”string”

    PagerSettings-Mode=”NextPrevious|Numeric|NextPreviousFirstLast|NumericFirstLast”

    PagerSettings-NextPageImageUrl=”uri”

    PagerSettings-NextPageText=”string”

    PagerSettings-PageButtonCount=”integer”

    PagerSettings-Position=”Bottom|Top|TopAndBottom”

    PagerSettings-PreviousPageImageUrl=”uri”

    PagerSettings-PreviousPageText=”string”

    PagerSettings-Visible=”True|False”

    PageSize=”integer”

    RowHeaderColumn=”string”

    runat=”server”

    SelectedIndex=”integer”

    ShowFooter=”True|False”

    ShowHeader=”True|False”

    SkinID=”string”

    Style=”string”

    TabIndex=”integer”

    ToolTip=”string”

    UseAccessibleHeader=”True|False”

    Visible=”True|False”

    Width=”size”

        <AlternatingRowStyle />

        <Columns>

 

                <asp:BoundField

                    AccessibleHeaderText=”string”

                    ApplyFormatInEditMode=”True|False”

                    ConvertEmptyStringToNull=”True|False”

                    DataField=”string”

                    DataFormatString=”string”

                    FooterText=”string”

                    HeaderImageUrl=”uri”

                    HeaderText=”string”

                    HtmlEncode=”True|False”

                    InsertVisible=”True|False”

                    NullDisplayText=”string”

                    ReadOnly=”True|False”

                    ShowHeader=”True|False”

                    SortExpression=”string”

                    Visible=”True|False”>

                        <ControlStyle />

                        <FooterStyle />

                        <HeaderStyle />

                        <ItemStyle />

                </asp:BoundField>

 

                <asp:ButtonField

                    AccessibleHeaderText=”string”

                    ButtonType=”Button|Image|Link”

                    CausesValidation=”True|False”

                    CommandName=”string”

                    DataTextField=”string”

                    DataTextFormatString=”string”

                    FooterText=”string”

                    HeaderImageUrl=”uri”

                    HeaderText=”string”

                    ImageUrl=”uri”

                    InsertVisible=”True|False”

                    ShowHeader=”True|False”

                    SortExpression=”string”

                    Text=”string”

                    ValidationGroup=”string”

                    Visible=”True|False”>

                        <ControlStyle />

                        <FooterStyle />

                        <HeaderStyle />

                        <ItemStyle />

                </asp:ButtonField>

 

                <asp:CheckBoxField

                    AccessibleHeaderText=”string”

                    DataField=”string”

                    FooterText=”string”

                    HeaderImageUrl=”uri”

                    HeaderText=”string”

                    InsertVisible=”True|False”

                    ReadOnly=”True|False”

                    ShowHeader=”True|False”

                    SortExpression=”string”

                    Text=”string”

                    Visible=”True|False”>

                        <ControlStyle />

                        <FooterStyle />

                        <HeaderStyle />

                        <ItemStyle />

                </asp:CheckBoxField>

 

                <asp:CommandField

                    AccessibleHeaderText=”string”

                    ButtonType=”Button|Image|Link”

                    CancelImageUrl=”uri”

                    CancelText=”string”

                    CausesValidation=”True|False”

                    DeleteImageUrl=”uri”

                    DeleteText=”string”

                    EditImageUrl=”uri”

                    EditText=”string”

                    FooterText=”string”

                    HeaderImageUrl=”uri”

                    HeaderText=”string”

                    InsertImageUrl=”uri”

                    InsertText=”string”

                    InsertVisible=”True|False”

                    NewImageUrl=”uri”

                    NewText=”string”

                    SelectImageUrl=”uri”

                    SelectText=”string”

                    ShowCancelButton=”True|False”

                    ShowDeleteButton=”True|False”

                    ShowEditButton=”True|False”

                    ShowHeader=”True|False”

                    ShowInsertButton=”True|False”

                    ShowSelectButton=”True|False”

                    SortExpression=”string”

                    UpdateImageUrl=”uri”

                    UpdateText=”string”

                    ValidationGroup=”string”

                    Visible=”True|False”>

                        <ControlStyle />

                        <FooterStyle />

                        <HeaderStyle />

                        <ItemStyle />

                </asp:CommandField>

 

                <asp:DynamicField

                    AccessibleHeaderText=”string”

                    ApplyFormatInEditMode=”True|False”

                    ConvertEmptyStringToNull=”True|False”

                    DataField=”string”

                    DataFormatString=”string”

                    FooterText=”string”

                    HeaderImageUrl=”uri”

                    HeaderText=”string”

                    HtmlEncode=”True|False”

                    InsertVisible=”True|False”

                    NullDisplayText=”string”

                    ShowHeader=”True|False”

                    UIHint=”string”

                    Visible=”True|False”>

                        <ControlStyle />

                        <FooterStyle />

                        <HeaderStyle />

                        <ItemStyle />

                </asp:DynamicField>

 

                <asp:HyperLinkField

                    AccessibleHeaderText=”string”

                    DataNavigateUrlFields=”string”

                    DataNavigateUrlFormatString=”string”

                    DataTextField=”string”

                    DataTextFormatString=”string”

                    FooterText=”string”

                    HeaderImageUrl=”uri”

                    HeaderText=”string”

                    InsertVisible=”True|False”

                    NavigateUrl=”uri”

                    ShowHeader=”True|False”

                    SortExpression=”string”

                    Target=”string|_blank|_parent|_search|_self|_top”

                    Text=”string”

                    Visible=”True|False”>

                        <ControlStyle />

                        <FooterStyle />

                        <HeaderStyle />

                        <ItemStyle />

                </asp:HyperLinkField>

 

                <asp:ImageField

                    AccessibleHeaderText=”string”

                    AlternateText=”string”

                    ConvertEmptyStringToNull=”True|False”

                    DataAlternateTextField=”string”

                    DataAlternateTextFormatString=”string”

                    DataImageUrlField=”string”

                    DataImageUrlFormatString=”string”

                    FooterText=”string”

                    HeaderImageUrl=”uri”

                    HeaderText=”string”

                    InsertVisible=”True|False”

                    NullDisplayText=”string”

                    NullImageUrl=”uri”

                    ReadOnly=”True|False”

                    ShowHeader=”True|False”

                    SortExpression=”string”

                    Visible=”True|False”>

                        <ControlStyle />

                        <FooterStyle />

                        <HeaderStyle />

                        <ItemStyle />

                </asp:ImageField>

 

                <asp:TemplateField

                    AccessibleHeaderText=”string”

                    ConvertEmptyStringToNull=”True|False”

                    FooterText=”string”

                    HeaderImageUrl=”uri”

                    HeaderText=”string”

                    InsertVisible=”True|False”

                    ShowHeader=”True|False”

                    SortExpression=”string”

                    Visible=”True|False”>

                            <ControlStyle />

                            <FooterStyle />

                            <HeaderStyle />

                            <ItemStyle />

                        <AlternatingItemTemplate>

                            <!– child controls –>

                        </AlternatingItemTemplate>

                        <EditItemTemplate>

                            <!– child controls –>

                        </EditItemTemplate>

                        <FooterTemplate>

                            <!– child controls –>

                        </FooterTemplate>

                        <HeaderTemplate>

                            <!– child controls –>

                        </HeaderTemplate>

                        <InsertItemTemplate>

                            <!– child controls –>

                        </InsertItemTemplate>

                        <ItemTemplate>

                            <!– child controls –>

                        </ItemTemplate>

                </asp:TemplateField>

        </Columns>

 

        <EditRowStyle />

        <EmptyDataRowStyle />

        <EmptyDataTemplate>

            <!– child controls –>

        </EmptyDataTemplate>

        <FooterStyle />

        <HeaderStyle />

        <PagerSettings

            FirstPageImageUrl=”uri”

            FirstPageText=”string”

            LastPageImageUrl=”uri”

            LastPageText=”string”

            Mode=”NextPrevious|Numeric|NextPreviousFirstLast|NumericFirstLast”

            NextPageImageUrl=”uri”

            NextPageText=”string”

            OnPropertyChanged=”PropertyChanged event handler”

            PageButtonCount=”integer”

            Position=”Bottom|Top|TopAndBottom”

            PreviousPageImageUrl=”uri”

            PreviousPageText=”string”

            Visible=”True|False”

        />

        <PagerStyle />

        <PagerTemplate>

            <!– child controls –>

        </PagerTemplate>

        <RowStyle />

        <SelectedRowStyle />

</asp:GridView>


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: