Grid View
Grid View
Grid View
0 GridView Control
ASP.NET 2.0 GridView Control
Description ....................................................................................................................................................................2
Step by step – Create a GridView Control to display data.............................................................................................3
GridView Control Fields .............................................................................................................................................5
Step by step – Create a GridView Control with editing enabled .................................................................................12
Databinding the GridView Control to a Datasource ....................................................................................................17
Postbacks.....................................................................................................................................................................18
GridView Control Events & Database Operations .......................................................................................................18
Event ‐ RowEditing...................................................................................................................................................18
Event ‐ RowCancelingEdit ........................................................................................................................................19
Event ‐ RowUpdating ...............................................................................................................................................19
Event ‐ RowDeleting ................................................................................................................................................20
Event – RowCommand ............................................................................................................................................21
GridView Control Quick Start ......................................................................................................................................22
Page | 1
ASP.NET 2.0 GridView Control
Description
See msdn.com for more info:
http://msdn2.microsoft.com/en‐us/library/system.web.ui.webcontrols.gridview(VS.80).aspx
The GridView Control belongs to the System.Web.UI.WebControls Namespace.
The GridView Control is a repeating control which renders out data in horizontal adjacent columns and displays the
values of a DataSource where each column represents a field and each row represents a record.
The example below shows a GridView Control bound to three fields, includes HeaderText and has been formatted
using CSS.
GridView Control
Above: Runtime view of the rendered GridView Control
The GridView Control also allows you to select, sort, and edit records via GridView Control events.
Locate the events belonging to the GridView Control by switching to code view and then selecting the name of
your GridView Control from the Class Name drop down list (left). Then click the arrow on the Method Name drop
down list (right).
GridView Control events
Page | 2
ASP.NET 2.0 GridView Control
Above: GridView Control events Method Name list.
Above: Larger view of GridView Control events as seen in the GridView Control Method Name list.
Step by step – Create a GridView Control to display data
1. Locate a GridView Control in the Data section of the Visual Studio Toolbox. Place onto the desired area of your
Web Form.
Page | 3
ASP.NET 2.0 GridView Control
2. With the GridView Control selected, locate the Properties pane and name the GridView Control (ID property).
3. With the GridView Control selected, locate the Smart Tag (small arrow) at the top right corner of the control &
click to open the GridView Tasks menu. Select Edit Columns to display the Fields dialog.
4. Uncheck the AutoGenerateFields checkbox. (If you leave this checked, the GridView Control will render out all
columns in the DataSource.)
Page | 4
ASP.NET 2.0 GridView Control
5. Select and add the desired Fields according to requirements. The table below outlines each Field available.
GridView Control Fields
BoundField The BoundField is used to display the value of a field as text.
Above: This example shows three fields from the DataSource (ProductName, Quantity and
Price) displayed in BoundFields. The last BoundField uses the DataFormatString property to
display the data as a dollar value.
To specify the field to display in a BoundField, set the DataField property to
the field's name such as ProductName.
As in the case of a field containing a dollar value, you can apply a formatting
string to the field's value by setting the DataFormatString property. In this
way, the text in the field will be displayed with a dollar sign.
Page | 5
ASP.NET 2.0 GridView Control
Examples:
DataField: The field from the DataSource you wish to display.
Eg. ProductName or Description or Price
DataFormatString: Use this field if you wish to format the data in a particular
way.
Eg. {0:c} will display a dollar value with a dollar sign
See msdn.com for more info:
http://msdn2.microsoft.com/en‐us/library/system.web.ui.webcontrols.boundfield(VS.80).aspx
CheckBoxField The CheckBoxField is used to display the value of a Boolean (True/False) data
field in a CheckBox.
To specify the field to display in a CheckBoxField, set the DataField property
with the field's name.
You can display a caption next to each CheckBox by setting the Text property.
Page | 6
ASP.NET 2.0 GridView Control
Examples:
DataField: The name of the field containing the Boolean data.
Eg. Subscribed or Paid
Text: The caption to be displayed next to the CheckBox.
Eg. Subscriber? Or Paid?
See msdn.com for more info:
http://msdn2.microsoft.com/en‐us/library/system.web.ui.webcontrols.checkboxfield(VS.80).aspx
HyperLinkField The HyperLinkField is used to display a hyperlink for each record displayed.
When the user clicks a hyperlink, he or she is directed to the web page
associated with the hyperlink.
Above: This simple GridView Control example displays the names of shopping categories in an
HyperLinkField.
Page | 7
ASP.NET 2.0 GridView Control
Set the DataTextField property to the field to be displayed, such as
ProductName.
To create a URL for navigation, set the DataNavigateUrlFields property to a
field to use to create the URL, such as ProductID.
By setting the DataNavigateUrlFormatString, you can set the page to
navigate to and include a QueryString. The value set in
DataNavigateUrlFields is inserted as the value of {0}.
In this example, at runtime the HyperLinkField will create a link that looks like
this: Products.aspx?ProductID=49
Examples:
DataNavigateUrlFields: The name of the field you want to pass in the Query
String.
Eg. ProductID or CustomerID or CartID
DataNavigateUrlFormatString: The URL to use with the
DatanavigateURLField.
Eg. Products.aspx?ProductID={0} or shoppingcart.aspx?CustomerID={0}
DataTextField: The name of the field to be displayed as the hyperlink.
Eg. ProductName or CustomerName or CategoryName
See msdn.com for more info:
http://msdn2.microsoft.com/en‐us/library/system.web.ui.webcontrols.hyperlinkfield(VS.80).aspx
ImageField The ImageField is used to display an image for each record displayed.
Page | 8
ASP.NET 2.0 GridView Control
Above: This GridView Control uses an ImageField to render out an image for each record of
the data source.
Set the DataImageUrlField property to the ID Field you are targeting. For
instance ‘ProductID’.
The URL value contains the path to the image file and can be formatted by
using the DataImageUrlFormatString property. The value set in
DataImageUrlField is inserted as the value of {0}.
In this example, at runtime the ImageField would create a path to an image
file which looks like this: productimages/49.gif
Examples:
DataImageUrlField: The ID of the record.
eg. ProductID or CategoryID or recordID
DataImageUrlFormatString: The path to the image file.
Eg. images/{0}.jpg or ProductImages/(0).jpg
See msdn.com for more info:
http://msdn2.microsoft.com/en‐us/library/system.web.ui.webcontrols.imagefield(VS.80).aspx
Page | 9
ASP.NET 2.0 GridView Control
ButtonField The ButtonField is used to display a button for each record that is displayed.
By creating a CommandName, clicking a button in a button field raises the
RowCommand event of the GridView control.
For instance:
If e.CommandName=”AddToCart” then
Code executes…
End If
To specify the type of button to display, use the ButtonType property.
When displaying a link or command button, use the Text property to specify
the caption to display in the buttons.
Examples:
ButtonType: Sets the button appearance.
Eg. Link or Button or Image
Text: The text to appear on the button.
Eg. Add to Cart or Add to Wishlist or Tell a Friend
CommandName: Provide a short, meaningful name for this button’s
Command so that it can be handled in the GridView RowCommand Event.
Eg. AddToCart or AddToWishList or TellFriend
See msdn.com for more info:
Page | 10
ASP.NET 2.0 GridView Control
http://msdn2.microsoft.com/en‐us/library/system.web.ui.webcontrols.buttonfield(VS.80).aspx
CommandField The CommandField is a special field used to display command buttons that
perform delete, edit, insert, or select operations.
By Default, each CommandField button is associated with a corresponding
Command. Each of these Commands raises a corresponding GridView Control
Event.
CommandField: Edit – raises the Gridview RowEditing event
CommandField: Update – raises the GridView RowUpdating event
CommandField: Cancel – raises the GridView RowCancelingEdit event
CommandField: Delete – raises the GridView RowDeleting event
CommandField: Select – raises the GridView SelectedIndexChanged event
To specify the type of button to display, use the ButtonType property.
See msdn.com for more info:
http://msdn2.microsoft.com/en‐
us/library/system.web.ui.webcontrols.commandfield(VS.80).aspx
TemplateField The TemplateField is used to display custom content for each record
displayed.
When you need to display content in a data‐bound control that is not
provided by one of the predefined data control fields in the GridView Control,
use the TemplateField class to create your custom user interface (UI).
Page | 11
ASP.NET 2.0 GridView Control
See msdn.com for more info:
http://msdn2.microsoft.com/en‐us/library/system.web.ui.webcontrols.templatefield(VS.80).aspx
Step by step – Create a GridView Control with editing
enabled
A GridView needs to be configured to enable editing on selected fields.
1. With the GridView Control selected, locate the Smart Tag (small arrow) at the top right corner of the control &
click to open the GridView Tasks menu. Select Edit Columns to display the Fields dialog.
2. In the fields list, expand the CommandField node and add an Edit, Update, Cancel CommandField. Leave the
CommandField Properties as default.
Page | 12
ASP.NET 2.0 GridView Control
3. Select the Field which is to have editing enabled and click the Convert this field into a TemplateField link.
Repeat this step for each field to have editing enabled. Click OK.
4. Open the GridView Tasks menu. Select Edit Templates to open the GridView Control in Template Editing Mode.
5. From the Display drop down list, select the name of a Template column (the name of the column will be the
same as what was specified in the HeaderText property of the field). Notice the ItemTemplate area contains an
unnamed control (in this example the control is called HyperLink1). This is the control which displays data that the
field is bound to. In this case, the field is bound to ProductName.
Page | 13
ASP.NET 2.0 GridView Control
6. In this example it is the text of ProductName that will be edited. Locate a TextBox control from the Toolbox and
drag it to the EditItemTemplate area.
Page | 14
ASP.NET 2.0 GridView Control
7. With the new TextBox selected, locate the Properties pane and give the TextBox a short meaningful name such
as txtEditProductName. The name of this control will be referred to during database operations.
NOTE: Some fields such as the HyperLinkField require an extra step to complete the databinding (the field
displayed in the control) within the EditItemTemplate.
1. Click the TextBox smart tag arrow and select Edit DataBindings to specify the text to be displayed in the textbox
during Editing.
2. Leave Bindable properties as Text and in the Custom Binding section, type Eval(“FieldName”) in the Code
Expression Textbox (FieldName being the name of the field to bind.)In this example, the field is bound to
ProductName therefore the Code expression is Eval(“ProductName”).
Page | 15
ASP.NET 2.0 GridView Control
3. Click OK.
Repeat steps 4 ‐ 7 for each field that requires editing. Click EndTemplate Editing when finished.
Example of an editable GridView Control
Above: The GridView Control with an Edit, Update, Cancel CommandField.
Above: The same GridView Control in Edit Mode.
<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="ProductName">
Page | 16
ASP.NET 2.0 GridView Control
<EditItemTemplate>
<asp:TextBox ID="txtEditProductName" runat="server" Text='<%# Eval("ProductName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("ProductID", "products.aspx?ProductID={0}") %>'
Text='<%# Eval("ProductName") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Price") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Price", "{0:c}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<RowStyle CssClass="norm" />
<HeaderStyle CssClass="header" />
</asp:GridView>
Above: Source view of the example GridView Control.
Databinding the GridView Control to a Datasource
It is helpful to create a custom routine to handle populating/refreshing controls such as the GridView Control. As
this control will need to be refreshed many times, this reusable component keeps the code that performs the
desired SELECT operation so that the routine may be called simply by name when required.
As well as the SELECT operation code, you will need to add the code responsible for performing the actual
databinding of the results to the GridView Control.
Create a procedure / event with a short meaningful name such as RefreshGridView and within it:
• The first task is to perform the SELECT operation
• The second task is databind the results of the SELECT to the GridView Control.
GridView Control Databinding properties and attributes:
DataSource ‐ The name of the Dataset
DataMember ‐ The name of the Query within the Dataset
DataKeyNames ‐ The field that contains the ID for each record.
DataBind – Go!
Page | 17
ASP.NET 2.0 GridView Control
Examine the code below:
Protected Sub RefreshGridView()
‘ Step 1.
' SELECT database operation goes here.........
‘ …………………………………………………………………
‘ …………………………………………………………………..
‘ Step 2.
‘ Databind the GridView to the results of the SELECT query.
Me.gvProducts.DataSource = dsResults
Me.gvProducts.DataMember = "GetAllProductsQuery"
Me.gvProducts.DataKeyNames = New String() {"ProductID"}
Me.gvProducts.DataBind()
End Sub
Postbacks
Watch out for Page Postbacks!!! The load event should only run the refresh code if the page is loading for the first
time.
Use Page.IsPostBack to check whether the page is being loaded in response to a client postback, or if it is being
loaded and accessed for the first time.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
RefreshGridView()
End If
End Sub
GridView Control Events & Database Operations
When performing Operations with the GridView Control, the code is contained within the events of the GridView
Control.
It is important to remember that any time an event fires, the final line of code should refresh the GridView Control.
Event ‐ RowEditing
The following shows the RowEditing event and sample code. This event fires when an Edit CommandButton is
clicked and executes code which opens any EditItemTemplates within the selected row.
• The first task is to put the GridView Control into Edit Mode.
Page | 18
ASP.NET 2.0 GridView Control
• The second task is to refresh the GridView Control.
Examine the code below:
Protected Sub gvProducts_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles
gvProducts.RowEditing
‘ Step 1.
‘ Put the GridView into Edit Mode for the selected row.
Me.gvProducts.EditIndex = e.NewEditIndex
‘ Step 2.
‘ Call the sub to Refresh the GridView
RefreshGridView()
End Sub
Event ‐ RowCancelingEdit
The following shows the RowCancelingEdit event and sample code. This event fires when a Cancel
CommandButton is clicked and executes code which closes any open EditItemTamplates within the selected row.
• The first task is to take the GridView Control out of Edit Mode.
• The second task is to refresh the GridView Control.
Examine the code below:
Protected Sub gvProducts_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs)
Handles gvProducts.RowCancelingEdit
‘ Step 1.
‘ Take the GridView out of Edit Mode.
Me.gvProducts.EditIndex = ‐1
‘ Step 2.
‘ Call the sub to Refresh the GridView
RefreshGridView()
End Sub
Event ‐ RowUpdating
The following shows the RowUpdating event and sample code. This event fires when an Update CommandButton
is clicked and executes code on the selected row.
• The first task is to harvest the record ID of the row to be updated. In this example, an Integer variable
called intSelectedID is created to hold this value. This value will be used to UPDATE the correct record.
• The second task is to declare each control in the EditItemTemplate of the GridView Control so that the
entered text or other value can be accessed.
• The third task is the UPDATE operation.
• The fourth task is to take the Gridview Control out of Edit Mode.
Page | 19
ASP.NET 2.0 GridView Control
• The fifth task is to refresh the GridView Control to reflect the changes.
Examine the code below:
Protected Sub gvProducts_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles
gvProducts.RowUpdating
‘ Step 1.
‘ Get ID of record selected.
Dim intSelectedID As Integer = Me.gvProducts.DataKeys(e.RowIndex).Value
‘ Step 2.
‘ Declare each control in the EditItemTemplate.
Dim txtEditProductName As TextBox = Me. gvProducts.Rows(e.RowIndex).FindControl("txtEditProductName ")
Dim txtEditPrice As TextBox = Me. gvProducts.Rows(e.RowIndex).FindControl("txtEditPrice ")
‘ Step 3.
' UPDATE Database Operation code goes here....
‘ ………………………………………………………………………..
‘ ……………………………………………………………………….
‘ Step 4.
‘ Take the GridView out of Edit Mode.
Me.gvProducts.editindex = ‐1
‘ Step 5.
‘ Call the sub to Refresh the GridView
RefreshGridView()
End Sub
Event ‐ RowDeleting
The following shows the RowDeleting event and sample code. This event fires when a Delete CommandButton is
clicked and executes code on the selected row.
The first line of code creates an Integer variable called intSelectedID to hold the ID of the record in the row to be
deleted. This value will be used to DELETE the correct record.
• The first task is to harvest the record ID of the row to be deleted. In this example, an Integer variable
called intSelectedID is created to hold this value. This value will be used to DELETE the correct record.
• The second task is the DELETE operation.
• The third task is to refresh the GridView Control to reflect the changes.
Examine the code below:
Protected Sub gvProducts_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles
gvProducts.RowDeleting
‘ Step 1.
‘ Get ID of record selected.
Dim intSelectedID As Integer = Me.gvProducts.DataKeys(e.RowIndex).Value
‘ Step 2.
' DELETE Database Operation code goes here....
‘ ………………………………………………………………………..
Page | 20
ASP.NET 2.0 GridView Control
‘ ……………………………………………………………………….
‘ Step 3.
‘ Call the sub to Refresh the GridView
RefreshGridView()
End Sub
Event – RowCommand
The following shows the RowCommand event and sample code. This event fires when a control containing a
CommandName is clicked and executes code for the appropriate Command on the selected row.
GridView Controls containing a CommandName property include the ButtonField as well as a variety of other
controls that may be added to a TemplateField such as an ImageButton.
Examine the code below:
Protected Sub gvShoppingCart_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
Handles gvShoppingCart.RowCommand
' Get the record ID of the item for which the command will execute.
Dim intCartItemID As Integer = e.CommandArgument
' If the CommandName of the CommandButton in the row = "Increase".
If e.CommandName = "Increase" Then
' Database operation goes here....
End If
' If the CommandName of the CommandButton in the row = "Decrease".
If e.CommandName = "Decrease" Then
' Database operation goes here....
End If
' If the CommandName of the CommandButton in the row = "Remove".
If e.CommandName = "Remove" Then
' Database operation goes here....
End If
End Sub
Page | 21
ASP.NET 2.0 GridView Control
Above: This example GridView Control includes 3 TemplateFields, each containing an ImageButton. Each image button has a CommandName
property. When one of the buttons is clicked, the GridView RowCommand event fires.
GridView Control Quick Start
1. Place a GridView onto your Web Form.
2. Add the columns/fields to be displayed and set the display and behaviour properties for each.
3. Bind Database results to the GridView Control.
If the contents of the GridView Control are to be editable:
4. Convert required columns to TemplateFields and add the required controls to the EditItemTemplate – giving
each a unique name.
Page | 22