Using the GridView Web Control - ASP.NET

This page show how to use the GridView control at its most basic level. An extender class exists to simplify the coding, and can be found here.

{outline||Step <1> - |.<1> - }

The ASP:GridView Tag

<asp:GridView runat=server" ID="uxMyGridView" AutoGenerateColumns="false" 
    CellPadding="3" CellSpacing="0" DataKeyNames="MyPrimaryKeyField(s)">

</asp:GridView>

DataBinding Code

If you want editing capabilities in your grid, then place the following code in its own method, so you can call it from several places on your page. The myDataTable variable is a DataTable created typically created from a database call.

uxMyGridView.DataSource = myDataTable;
uxMyGridView.DataBind();

Grid Columns

Columns are added to the GridView within the <Columns> of the <asp:GridView> tag, as shown in the following example.

ControlUsageNote
asp:BoundField Simple data-bound column with little customization possible.Fields shown as Labels are unconditionally changed to TextBoxes when in edit mode, unless you specify the ReadOnly property to true for the column.
asp:TemplateFieldCommonly used with editable fieldsWhen using the Eval function, enclose the attribute value single quotes rather than the default double quotes.
asp:CommandFieldProvides controls used to trigger editing functions on the row 

<asp:GridView runat=server" ID="uxMyGridView" AutoGenerateColumns="false" 
    CellPadding="3" CellSpacing="0" DataKeyNames="MyPrimaryKeyField(s)" >

    <Columns>

        <asp:BoundField DataField="MyDataField" HeaderText="MyHeader" />

        <asp:TemplateField HeaderText="Description">
            <ItemTemplate>
                <asp:Label runat=server 
                    Text='<%# Eval("Description") %>' 
                     />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox runat="server"
                    ID="uxDescriptionTextBox"
                    Text='<%# Eval("Description") %>'
                    />
            </EditItemTemplate>
        </asp:TemplateField>

        <asp:CommandField HeaderText="Action" ButtonType="Image" 
            DeleteText="Delete" ShowDeleteButton="true" DeleteImageUrl="~/images/Delete.png"
            EditText="Edit" ShowEditButton="true" EditImageUrl="~/images/Pencil.png"
            CancelText="Cancel" ShowCancelButton="true" CancelImageUrl="~/images/StopSign.png"
            UpdateText="Save" UpdateImageUrl="~/images/Save.png"
            ShowSelectButton="false"
            />

    </Columns>

</asp:GridView>

Adding Editing Functions

A key element to adding edit functionality to the GridView is the asp:CommandField column which is capable of automatically handling the rendering of the following command buttons: Edit, Cancel, Update, Delete, and Insert. Sample code for these buttons is shown below.

The Edit Button

The following VB code is triggered when the user clicks an Edit button (in the CommandField column). In C#, the binding to the event is done in the ASP code via the OnRowEditing property of the asp:GridView control.

Protected Sub uxMyGridView_RowEditing(ByVal sender As Object, ByVal e As _
    GridViewEditEventArgs) Handles uxMyGridView.RowEditing

    Dim grid As GridView = CType(sender, GridView)
    grid.EditIndex = e.NewEditIndex
    BindMyGrid()

End Sub

The Cancel Button

The following VB code is triggered when the user clicks a Cancel button, which appears when a row is in edit mode. In C#, the binding to the event is done in ASP code via the OnRowCancelingEdit property of the asp:GridView control.

Protected Sub uxMyGridView_RowEditingCancelled(ByVal sender As Object, ByVal e As _
GridViewCancelEditEventArgs) Handles uxMyGridView.RowCancelingEdit

    Dim grid As GridView = CType(sender, GridView)
    grid.EditIndex = -1
    BindMyGrid()

End Sub

The Update Button

The following VB code is triggered when the user clicks an Update button, which appears when a row is in edit mode. In C#, the binding to the event is done in ASP code via the OnRowUpdating property of the asp:GridView control. Note that the Keys, OldValues, and NewValues collections (of the GridViewUpdateEventArgs parameter) are automatically populated only when the GridView control is bound to data by using the DataSourceID property.

Protected Sub uxMyGridView_RowUpdate(ByVal sender As Object, ByVal e As _
GridViewUpdateEventArgs) Handles uxMyGridView.RowUpdating

    Dim gv As GridView = CType(sender, GridView)
    Dim gvRow As GridViewRow = gridView.Rows(e.RowIndex)
    Dim rowKey as DataKey = gv.DataKeys(e.RowIndex)

    Dim id as Integer = Convert.ToInt32(rowKey("ID"))
    dim description as String = CType(gvRow.FindControl("uxDescriptionTextBox"), TextBox).Text

    ' Submit data to database for updating

    gv.EditIndex = -1

    BindMyGrid()

End Sub

The Delete Button

Client-Side (User Confirmation)

The following VB code demonstrates how to provide for user confirmation before deleting a row from the grid view. A few things may be different in your implementation.


Protected Sub uxMyGridView_RowDataBound(ByVal sender As Object, ByVal e As _
GridViewRowEventArgs) Handles uxMyGridView.RowDataBound

    Try

        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim dataRow As DataRow = CType(e.Row.DataItem, DataRowView).Row
            Dim fileName As String = dataRow("FileName").ToString()

            Dim deleteButton As ImageButton = e.Row.Cells(3).Controls(2)
            deleteButton.OnClientClick = "confirm('Delete [" & fileName & "]?');"

        End If

    Catch ex As Exception

        Throw ex

    End Try

End Sub

Server Side (Data Access)

The following VB code is triggered when the user clicks a Delete button, which appears when a row is in edit mode. In C#, the binding to the event is done in ASP code via the OnRowDeleting property of the asp:GridView control.

Protected Sub uxMyGridView_RowDeleting(ByVal sender As Object, ByVal e As _
GridViewDeleteEventArgs) Handles uxMyGridView.RowDeleting

    Dim gv As GridView = CType(sender, GridView)
    Dim gvRow As GridViewRow = gv.Rows(e.RowIndex)
    Dim rowKey As DataKey = gv.DataKeys(e.RowIndex)
    Dim id As Integer = Convert.ToInt32(rowKey("ID"))

    Globals.Database.DeleteItem(id)

    gv.EditIndex = -1
    BindMyGrid()

End Sub