GridView, Repeater and ListView in ASP.NET: binding, paging, selection, highlighting and printing
Admin pages in Web Forms are mostly lists: orders, customers, files, log lines. Three controls render them. The Repeater outputs exactly the markup you write and nothing else. The ListView adds templates for editing and works with the DataPager. The GridView renders a table and brings sorting, paging, selection and editing out of the box. This guide follows the life of such a list: binding it, paging it, letting users select rows, making the selection visible, printing the result and editing rows in place. The examples share one principle: put the identifiers you need in DataKeyNames or data attributes, and read those rather than the text of the cells.
Repeater, ListView or GridView?
| Need | Repeater | ListView | GridView |
|---|---|---|---|
| Markup control | Total | Total | A <table> |
| Paging | Manual (PagedDataSource) | With DataPager | Built in (AllowPaging) |
| Selection, editing | By hand with commands | Edit and insert templates | Built-in Select, Edit, Delete |
| Typical use | Cards, menus, simple lists | Custom layouts with paging | Admin tables |
Binding a Repeater
Start with the lightest control: everything the GridView does later is optional extra on top of this binding pattern.
The Repeater is the simplest data-bound control in Web Forms: it renders a template once per item and adds nothing of its own. No table, no styles, no paging. That makes it ideal for lists, cards and any markup the GridView cannot produce.
Markup
<asp:Repeater ID="rptArticles" runat="server" ItemType="Demo.ArticleSummary"
OnItemDataBound="rptArticles_ItemDataBound" OnItemCommand="rptArticles_ItemCommand">
<HeaderTemplate><ul class="articles"></HeaderTemplate>
<ItemTemplate>
<li>
<a href='<%# "Article.aspx?id=" + Item.Id %>'><%#: Item.Title %></a>
<time datetime='<%# Item.Published.ToString("yyyy-MM-dd") %>'><%# Item.Published.ToString("d MMM yyyy") %></time>
<asp:Label ID="lblNew" runat="server" CssClass="badge" Text="New" Visible="false" />
<asp:LinkButton runat="server" CommandName="Archive" CommandArgument='<%# Item.Id %>' Text="Archive" />
</li>
</ItemTemplate>
<FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
<asp:PlaceHolder ID="phEmpty" runat="server" Visible="false"><p>No articles yet.</p></asp:PlaceHolder>
Templates: HeaderTemplate and FooterTemplate render once, ItemTemplate per item, AlternatingItemTemplate (optional) for every second item, SeparatorTemplate between items. Note that the opening <ul> in the header and the closing tag in the footer form one element in the output.
ItemType (.NET 4.5 and later) gives strongly typed access through Item, checked at compile time. Without it, use Eval("Title"), which resolves the property by name at run time.
Code-behind
public class ArticleSummary
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime Published { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) Bind();
}
private void Bind()
{
var list = new List<ArticleSummary>();
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["Db"].ConnectionString))
using (var cmd = new SqlCommand(
"SELECT TOP (20) ArticleId, Title, PublishedOn FROM dbo.Articles WHERE Archived = 0 ORDER BY PublishedOn DESC", con))
{
con.Open();
using (var r = cmd.ExecuteReader())
while (r.Read())
list.Add(new ArticleSummary { Id = r.GetInt32(0), Title = r.GetString(1), Published = r.GetDateTime(2) });
}
rptArticles.DataSource = list;
rptArticles.DataBind();
phEmpty.Visible = list.Count == 0;
}
protected void rptArticles_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
var a = (ArticleSummary)e.Item.DataItem;
e.Item.FindControl("lblNew").Visible = a.Published > DateTime.Today.AddDays(-7);
}
protected void rptArticles_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Archive" && int.TryParse((string)e.CommandArgument, out int id))
{
ArticleRepository.Archive(id);
Bind();
}
}
ItemDataBoundruns for every template, including header and footer, hence theItemTypecheck before readingDataItem.ItemCommandcatches the commands of all buttons in the items.CommandArgumentarrives as a string.- The Repeater has no
EmptyDataTemplate; the placeholder handles the empty case.
Paging is not built in; see Paging a Repeater. For a table with editing and sorting, the GridView is the better fit: Bind a GridView.
Paging a Repeater, or using a ListView with a DataPager
The Repeater's weakness is paging. There are two ways round it.
The Repeater gives total control over markup but has no paging. The DataPager control only works with controls that implement IPageableItemContainer, which in the box means the ListView. So you either page the Repeater yourself, or use a ListView, whose templates are as free as a Repeater's.
Option 1: Repeater with PagedDataSource
<asp:Repeater ID="rptNews" runat="server" ItemType="Demo.NewsItem">
<ItemTemplate>
<article><h3><%#: Item.Title %></h3><p><%#: Item.Summary %></p></article>
</ItemTemplate>
</asp:Repeater>
<asp:Repeater ID="rptPager" runat="server" OnItemCommand="rptPager_ItemCommand">
<HeaderTemplate><nav class="pager" aria-label="Pages"></HeaderTemplate>
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="Page" CommandArgument='<%# Container.DataItem %>'
Text='<%# (int)Container.DataItem + 1 %>'
Enabled='<%# (int)Container.DataItem != CurrentPage %>' />
</ItemTemplate>
<FooterTemplate></nav></FooterTemplate>
</asp:Repeater>
public partial class News : Page
{
private const int PageSize = 5;
protected int CurrentPage
{
get => (int)(ViewState["page"] ?? 0);
set => ViewState["page"] = value;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) Bind();
}
private void Bind()
{
List<NewsItem> all = NewsRepository.All(); // ordered list
var pds = new PagedDataSource
{
DataSource = all,
AllowPaging = true,
PageSize = PageSize,
CurrentPageIndex = Math.Min(CurrentPage, Math.Max(0, (all.Count - 1) / PageSize))
};
rptNews.DataSource = pds;
rptNews.DataBind();
rptPager.DataSource = Enumerable.Range(0, pds.PageCount);
rptPager.DataBind();
rptPager.Visible = pds.PageCount > 1;
}
protected void rptPager_ItemCommand(object source, RepeaterCommandEventArgs e)
{
CurrentPage = Convert.ToInt32(e.CommandArgument);
Bind();
}
}
PagedDataSource wraps any IEnumerable that supports counting (a list, a DataView…) and exposes only the current page. The pager is just another Repeater bound to page numbers. A disabled LinkButton renders without a link, marking the current page.
This loads every row and keeps one page; for large tables, query only the page you need with OFFSET … FETCH and compute the page count from a COUNT(*).
Option 2: ListView with DataPager
<asp:ListView ID="lvNews" runat="server" ItemType="Demo.NewsItem"
SelectMethod="GetNews" ItemPlaceholderID="ph">
<LayoutTemplate>
<div class="news"><asp:PlaceHolder ID="ph" runat="server" /></div>
<asp:DataPager ID="dp" runat="server" PageSize="5" PagedControlID="lvNews">
<Fields><asp:NumericPagerField ButtonCount="10" /></Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<article><h3><%#: Item.Title %></h3><p><%#: Item.Summary %></p></article>
</ItemTemplate>
</asp:ListView>
public IQueryable<NewsItem> GetNews()
{
return NewsRepository.All().AsQueryable();
}
With model binding (SelectMethod, .NET 4.5 and later), the ListView handles page changes itself. Return an IQueryable from Entity Framework and the paging is translated to SQL. The DataPager can also stand outside the ListView if PagedControlID points to it.
Which to choose
For new pages, the ListView is less code and gives the same freedom of markup. Keep the Repeater approach when you are adding paging to an existing Repeater with many templates and event handlers. The basics of the Repeater are in Bind a Repeater control.
Reading the selected GridView row
With a GridView, the first server-side task is usually to find out which row the user picked.
When a user clicks Select on a GridView row, the server needs that row's values: an id to load a record, a name to show in a form. There are several ways to read them, and the most robust one does not read the cells at all.
The grid
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"
DataKeyNames="CustomerId,Country" OnSelectedIndexChanged="gvCustomers_SelectedIndexChanged"
SelectedRowStyle-CssClass="is-selected">
<Columns>
<asp:CommandField ShowSelectButton="true" SelectText="Select" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:TemplateField HeaderText="Credit limit">
<ItemTemplate>
<asp:Label ID="lblLimit" runat="server" Text='<%# Eval("CreditLimit", "{0:N0}") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblInfo" runat="server" />
Reading the selection
protected void gvCustomers_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = gvCustomers.SelectedRow;
// 1. Keys: reliable, typed, not shown in the grid
int id = (int)gvCustomers.SelectedDataKey.Values["CustomerId"];
string country = (string)gvCustomers.SelectedDataKey.Values["Country"];
// 2. A BoundField cell: text is HTML-encoded
string name = HttpUtility.HtmlDecode(row.Cells[1].Text);
// 3. A control in a TemplateField
string limit = ((Label)row.FindControl("lblLimit")).Text;
lblInfo.Text = $"#{id} {HttpUtility.HtmlEncode(name)} ({HttpUtility.HtmlEncode(country)}), limit {limit}";
}
- DataKeys are stored in control state and do not depend on column order or formatting. Use them for anything you will query with.
- Cells are indexed by column position, including the select column, and contain encoded, formatted text. An empty value appears as
. Fine for display, fragile for logic. - FindControl reads controls inside template fields by their id.
Buttons in the row instead of Select
A button with a custom command passes the row through CommandArgument:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" Text="Details" CommandName="ShowDetails"
CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
protected void gvCustomers_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName != "ShowDetails") return;
int index = Convert.ToInt32(e.CommandArgument) - gvCustomers.PageIndex * gvCustomers.PageSize;
int id = (int)gvCustomers.DataKeys[index].Value;
ShowCustomer(id);
}
Container.DataItemIndex counts across all pages, while DataKeys and Rows only hold the current page, hence the subtraction when paging is on. Alternatively use Container.DisplayIndex, which is the index within the page.
Styling the selected row
.is-selected td { background: #fff3c4; font-weight: 600; }
Reset the selection with gvCustomers.SelectedIndex = -1; after rebinding to other data, or the same row index stays selected for a different record.
A full form built on this pattern: Insert, edit, update and delete with a form and a GridView. Reading row values in the browser: GridView row values with jQuery.
Common mistakes
- Reading
SelectedRowinPage_Load: the selection event has not run yet. Read it inSelectedIndexChangedor later. - Rebinding the grid before reading the selection: rebinding recreates the rows and the selected index may then point at different data.
- Using
Cells[n].Textfor template columns: it is empty, because the content is in child controls. UseFindControl.
A check-all box in the header
Multi-row actions (delete, export, e-mail) need check boxes, and a header box that ticks them all.
A check box in the header that selects every row is standard in admin grids. In Web Forms the boxes are server controls inside a TemplateField; jQuery handles the clicking in the browser, and the server reads the result on postback as usual.
Markup
<asp:GridView ID="gvMail" runat="server" AutoGenerateColumns="false" DataKeyNames="MessageId" CssClass="grid">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" CssClass="check-all" ToolTip="Select all" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" CssClass="check-row" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Subject" HeaderText="Subject" />
<asp:BoundField DataField="Received" HeaderText="Received" DataFormatString="{0:g}" />
</Columns>
</asp:GridView>
<asp:Button ID="btnDelete" runat="server" Text="Delete selected" OnClick="btnDelete_Click" />
An asp:CheckBox renders the CssClass on a <span> that wraps the <input>, not on the input itself. The selectors below therefore look for the input inside the span: .check-row input.
jQuery
$(function () {
var $grid = $(".grid");
function rows() { return $grid.find(".check-row input[type=checkbox]"); }
function header() { return $grid.find(".check-all input[type=checkbox]"); }
// header -> rows
$grid.on("change", ".check-all input", function () {
rows().prop("checked", this.checked);
header().prop("indeterminate", false);
});
// rows -> header
$grid.on("change", ".check-row input", function () {
var total = rows().length, checked = rows().filter(":checked").length;
header().prop({ checked: total > 0 && checked === total,
indeterminate: checked > 0 && checked < total });
});
});
The indeterminate property shows a dash in the header box when only some rows are selected. It is a visual state only: it is never posted, and the server sees the header box as unchecked.
Reading the selection on the server
protected void btnDelete_Click(object sender, EventArgs e)
{
var ids = new List<int>();
foreach (GridViewRow row in gvMail.Rows)
{
if (row.RowType != DataControlRowType.DataRow) continue;
var chk = (CheckBox)row.FindControl("chkRow");
if (chk.Checked) ids.Add((int)gvMail.DataKeys[row.RowIndex].Value);
}
if (ids.Count == 0) return;
MailRepository.Delete(ids); // one parameterised statement, or a table-valued parameter
BindGrid();
}
Check boxes changed by script are posted like any others, so chk.Checked reflects what the user sees. Bind the grid only when !IsPostBack in Page_Load, otherwise the boxes are recreated unchecked before the click handler runs. Deleting a list of ids in one call is shown in Passing a DataTable as a table-valued parameter.
Variations
- Highlight the selected rows: Highlight a GridView row when its check box is ticked.
- Keep selections across pages: Keep checked rows with paging.
- Without jQuery:
document.querySelectorAll(".check-row input").forEach(cb => cb.checked = all.checked).
Common mistakes
- Selecting
.check-rowand settingcheckedon it: the class is on the wrapping span, not the input. - Binding the handlers once, then refreshing the grid in an
UpdatePanel: delegate from a container outside the panel, or rebind inpageLoad(). - Trusting the header box on the server: it is not a reliable "all rows" flag, especially with paging. Read each row.
Keeping check boxes ticked across pages
As soon as the grid is paged, those ticks disappear when the user changes page, unless the page remembers them.
A paged GridView only renders the rows of the current page. Tick three rows on page 1, move to page 2, come back, and the ticks are gone: the grid was rebound and the check boxes were recreated empty. The fix is to remember the selected keys yourself, in view state, and restore them after each bind.
Markup
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false" AllowPaging="true" PageSize="10"
DataKeyNames="UserId" OnPageIndexChanging="gvUsers_PageIndexChanging" OnRowDataBound="gvUsers_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate><asp:CheckBox ID="chkSelect" runat="server" /></ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UserName" HeaderText="User" />
<asp:BoundField DataField="Email" HeaderText="E-mail" />
</Columns>
</asp:GridView>
<asp:Button ID="btnDisable" runat="server" Text="Disable selected users" OnClick="btnDisable_Click" />
<asp:Label ID="lblResult" runat="server" />
Code-behind
public partial class Users : Page
{
// Selected keys across all pages
private HashSet<int> Selected
{
get
{
if (!(ViewState["Selected"] is HashSet<int> set))
{
set = new HashSet<int>();
ViewState["Selected"] = set;
}
return set;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) BindGrid();
}
private void BindGrid()
{
gvUsers.DataSource = UserRepository.All(); // DataTable or List, ordered
gvUsers.DataBind();
}
// Copy the check boxes of the visible page into the set
private void SaveCurrentPage()
{
foreach (GridViewRow row in gvUsers.Rows)
{
int id = (int)gvUsers.DataKeys[row.RowIndex].Value;
var chk = (CheckBox)row.FindControl("chkSelect");
if (chk.Checked) Selected.Add(id); else Selected.Remove(id);
}
}
protected void gvUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
SaveCurrentPage(); // before the rows disappear
gvUsers.PageIndex = e.NewPageIndex;
BindGrid();
}
protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow) return;
int id = (int)gvUsers.DataKeys[e.Row.RowIndex].Value;
((CheckBox)e.Row.FindControl("chkSelect")).Checked = Selected.Contains(id);
}
protected void btnDisable_Click(object sender, EventArgs e)
{
SaveCurrentPage(); // include changes on the page being shown
if (Selected.Count == 0) { lblResult.Text = "Nothing selected."; return; }
UserRepository.Disable(Selected);
lblResult.Text = Selected.Count + " user(s) disabled.";
Selected.Clear();
BindGrid();
}
}
Why it works
PageIndexChangingfires before the grid is rebound, whilegvUsers.Rowsstill holds the old page with the posted check box states. That is the only moment to read them.DataKeysare available inRowDataBoundfor the row being bound, so each row can be restored by key.HashSet<int>is serialisable, so it can live in view state; keys are small, so the page grows little. For thousands of selections, keep them in session state instead.- Keys, not row indexes, are stored: the same index means a different user on another page.
A "select all" box for the current page is shown in Check or uncheck all CheckBoxes with jQuery; it combines well with this technique because script-ticked boxes are posted like any others.
If UserRepository.Disable runs one statement per id, consider a single call with a table-valued parameter: Passing a DataTable as a table-valued parameter.
Reading row values in the browser
Some reactions to a row should not cost a postback at all.
Sometimes the browser should react to a row without a postback: fill a dialog, enable a toolbar, compute a total. A GridView renders an ordinary <table>, so jQuery can read any row. The trick is to put the values you need in the markup in a form that is easy to read.
Markup: HiddenField or data attributes
<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="false" CssClass="products">
<Columns>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:HiddenField ID="hfId" runat="server" Value='<%# Eval("ProductId") %>' />
<span class="name"><%#: Eval("Name") %></span>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Stock" HeaderText="Stock" />
<asp:TemplateField>
<ItemTemplate>
<button type="button" class="pick" data-id='<%# Eval("ProductId") %>'
data-price='<%# ((decimal)Eval("Price")).ToString(System.Globalization.CultureInfo.InvariantCulture) %>'>Pick</button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<p>Selected: <span id="picked">none</span></p>
An asp:HiddenField renders <input type="hidden"> with a generated id per row; its id looks like gvProducts_hfId_0, so find it relative to the row rather than by id. A data- attribute on the button is even simpler to read.
jQuery
$(function () {
$(".products").on("click", "button.pick", function () {
var $row = $(this).closest("tr");
var idFromHidden = $row.find("input[type=hidden]").first().val(); // ids end in _0, _1…
var idFromData = $(this).data("id"); // number, converted by jQuery
var price = parseFloat($(this).attr("data-price"));
var name = $row.find(".name").text();
var stock = parseInt($row.children("td").eq(1).text(), 10);
$(".products tr").removeClass("is-picked");
$row.addClass("is-picked");
$("#picked").text(name + " (#" + idFromData + "), " + price.toFixed(2) + ", stock " + stock);
});
});
Delegating from the table (.on("click", "button.pick", …)) needs one handler for all rows and keeps working when the grid is refreshed inside an UpdatePanel, as long as the table element itself is replaced along with its rows; if it is, bind to a container outside the panel instead.
.data("id") converts numeric-looking values to numbers; use .attr("data-id") to get the exact string, for example for ids with leading zeros.
Sending the choice back to the server
Put the selected id in a page-level HiddenField outside the grid, then post normally:
$("#<%= hfSelectedId.ClientID %>").val(idFromData);
protected void btnContinue_Click(object sender, EventArgs e)
{
if (int.TryParse(hfSelectedId.Value, out int id)) LoadProduct(id); // validate: the client can send anything
}
On the server side, reading the selected row without script is covered in GridView selected row in code-behind.
Common mistakes
- Looking up a row's HiddenField by its server
ID: the rendered id has a row suffix. Search inside the row. - Counting cells by position when columns may be hidden:
Visible="false"columns are not rendered at all, so indexes shift. Prefer classes or data attributes. - Trusting values read in the browser for prices or permissions: they can be edited in the developer tools. Look them up again on the server by id.
Highlighting ticked rows
Once rows can be ticked, show which ones are.
In a grid where users tick rows before an action, a coloured background on the ticked rows shows the selection at a glance. jQuery toggles a class when a box changes; the server applies the same class after a postback; and in recent browsers, CSS alone can do it.
Markup and CSS
<asp:GridView ID="gvTasks" runat="server" AutoGenerateColumns="false" DataKeyNames="TaskId"
CssClass="tasks" OnRowDataBound="gvTasks_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate><asp:CheckBox ID="chkRow" runat="server" CssClass="row-check" /></ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Title" HeaderText="Task" />
<asp:BoundField DataField="Owner" HeaderText="Owner" />
</Columns>
</asp:GridView>
<style>
.tasks tr.is-checked td { background: #e6f4f1; }
.tasks tr.is-checked td:first-child { box-shadow: inset 4px 0 0 #0e6a70; }
</style>
The extra inset bar on the first cell keeps the selection visible to users who do not perceive the background colour difference.
jQuery
$(function () {
var $grid = $(".tasks");
// check box -> row class
$grid.on("change", ".row-check input", function () {
$(this).closest("tr").toggleClass("is-checked", this.checked);
});
// click anywhere on the row toggles the box (but not when clicking links or the box itself)
$grid.on("click", "tr", function (e) {
if ($(e.target).is("a, input, label, button")) return;
var $cb = $(this).find(".row-check input");
if ($cb.length) $cb.prop("checked", !$cb.prop("checked")).trigger("change");
});
// initial state (e.g. after a postback)
$grid.find(".row-check input:checked").closest("tr").addClass("is-checked");
});
The CssClass of an asp:CheckBox goes on a wrapping <span>, hence the selector .row-check input. Setting checked from script does not raise change, so the row click triggers it explicitly.
Server side after postback
The initial-state line above already restores the highlight from the posted check boxes. If you set the boxes from data on the server, add the class there too, so the row is correct even before scripts run:
protected void gvTasks_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow) return;
var task = (TaskItem)e.Row.DataItem;
var chk = (CheckBox)e.Row.FindControl("chkRow");
chk.Checked = task.Flagged;
if (chk.Checked) e.Row.CssClass += " is-checked";
}
CSS only with :has()
The :has() selector, supported by current versions of all major browsers, styles a row according to its content, without any script:
.tasks tr:has(.row-check input:checked) td { background: #e6f4f1; }
Keep the jQuery version if you must support older browsers, or use it as a fallback alongside the CSS rule.
Related
- Check or uncheck all rows from a header box.
- Highlight the row under the mouse.
- Keep selections across pages.
Accessibility notes
The highlight is a visual aid; the state that assistive technology reads is the check box itself, so every box needs an accessible name. A box in a grid row has no visible label of its own: add one with InputAttributes, for example chk.InputAttributes["aria-label"] = "Select task " + task.Title; in RowDataBound. Making the whole row clickable is convenient for mouse users; keyboard users still use the box, which remains focusable.
Highlighting the row under the pointer
Hover highlighting is purely visual and, today, purely CSS.
Long tables are easier to read when the row under the pointer stands out. Old Web Forms tutorials added onmouseover attributes to every row from RowDataBound, or used jQuery. CSS has done this alone for years, with a smooth transition and without touching the code-behind.
CSS
<asp:GridView ID="gvOrders" runat="server" CssClass="grid" AutoGenerateColumns="true" />
.grid { border-collapse: collapse; width: 100%; }
.grid th, .grid td { padding: .45rem .6rem; border-bottom: 1px solid #d9dee5; text-align: left; }
/* zebra striping on data rows (the header row uses th) */
.grid tr:nth-child(even) td { background: #f6f8fa; }
/* hover and keyboard focus */
.grid td { transition: background-color .15s ease; }
.grid tr:hover td,
.grid tr:focus-within td { background: #fff1c2; }
The rule targets cells (td) rather than the row: background colours on tr are painted under the cells' own backgrounds, so a striped cell would hide a row-level hover colour. :focus-within also highlights the row when a link or button inside it has keyboard focus, so the effect is not reserved for mouse users.
A GridView with a pager renders the pager in its own table row; if your selectors match it, exclude it with a PagerStyle-CssClass and a rule such as .grid tr.pager:hover td { background: none; }.
The jQuery version
You may meet this in older projects. It does the same as the CSS rule, with more code:
$(function () {
$(".grid").on("mouseenter", "tr:has(td)", function () {
$(this).addClass("is-hover");
}).on("mouseleave", "tr:has(td)", function () {
$(this).removeClass("is-hover");
});
});
Script is still useful when the hover must do more than change style, such as showing a preview panel for the row. For pure styling, remove it and use CSS.
The RowDataBound attribute approach
// Old pattern, not recommended
e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='#fff1c2';";
e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='';";
It mixes presentation into server code, adds script to every row's HTML, and breaks under a Content Security Policy that forbids inline event handlers. If you maintain such code, replacing it with the CSS above is a safe, purely visual change.
Making whole rows clickable
A highlighted row invites a click. If clicking should open the record, put a real link in the first cell and stretch it with CSS, so keyboard and screen-reader users get the same function:
.grid tr { position: relative; }
.grid td:first-child a::after { content: ""; position: absolute; inset: 0; }
Positioning on table rows is supported in current browsers; test with your target browsers.
Highlighting rows that are ticked rather than hovered: Highlight checked GridView rows. More on transitions: Fade in and out with a CSS3 transition.
Printing a GridView
A grid often ends up on paper. The browser can print just the table if the page tells it how.
Users want a "Print" button that prints the table, not the menu, the filters and the footer. The modern answer is a print stylesheet plus window.print(); the browser does the rest, including repeating the header row on every printed page.
The button
<div class="report">
<h2>Open orders</h2>
<asp:GridView ID="gvOrders" runat="server" CssClass="grid" UseAccessibleHeader="true" />
</div>
<button type="button" class="no-print" onclick="window.print()">Print</button>
UseAccessibleHeader="true" renders the header cells as <th> in a <thead> (when combined with the line below), which helps screen readers and printing.
protected void Page_PreRender(object sender, EventArgs e)
{
if (gvOrders.HeaderRow != null)
gvOrders.HeaderRow.TableSection = TableRowSection.TableHeader; // emits <thead>
}
The print stylesheet
@media print {
header.site, nav, footer.site, .no-print, .filters { display: none !important; }
body { background: #fff; color: #000; font-size: 11pt; }
.report { margin: 0; }
.grid { width: 100%; border-collapse: collapse; }
.grid th, .grid td { border: 1px solid #999; padding: 3pt 5pt; }
.grid thead { display: table-header-group; } /* repeat the header on each page */
.grid tr { break-inside: avoid; } /* do not split a row across pages */
a[href]::after { content: ""; } /* no URLs after links */
}
Everything not needed on paper is hidden; the table gets plain borders that survive black-and-white printing. Browsers repeat <thead> rows at the top of each printed page.
Printing every page of a paged grid
A paged GridView only contains the current page. To print everything, rebind without paging on a postback and print when the page reloads:
protected void btnPrintAll_Click(object sender, EventArgs e)
{
gvOrders.AllowPaging = false;
BindGrid();
ClientScript.RegisterStartupScript(GetType(), "print", "window.print();", true);
}
On the next postback paging is back, because AllowPaging is only changed for this response. For very large grids, a PDF export is kinder to the browser: see Export GridView data.
The popup technique
Older tutorials copy the grid's HTML into a new window and print that:
function printGrid() {
var html = document.getElementById("<%= gvOrders.ClientID %>").outerHTML;
var w = window.open("", "_blank", "width=900,height=700");
w.document.write("<!doctype html><title>Orders</title><link rel=stylesheet href='/print.css'>" + html);
w.document.close();
w.onload = function () { w.focus(); w.print(); w.close(); };
}
It works but popup blockers may interfere, styles must be loaded again, and document.write is discouraged. The print stylesheet approach is simpler and also applies when users press Ctrl+P.
Common problems
- Colours disappear on paper. Browsers do not print backgrounds by default. Use borders and bold text for emphasis, or
print-color-adjust: exactwhere colour is essential. - The table is cut on the right. Too many columns for the page width: hide less important columns in the print stylesheet, reduce the font size, or set
@page { size: landscape; }. - The print button prints the button. Give it the
no-printclass.
Inline insert, edit, update and delete
Finally, the GridView can edit its own rows. This is the full example, with parameterised SQL.
The GridView can edit its own rows: one click turns a row's labels into text boxes, another saves the changes. Add a footer row with empty boxes and the same grid also inserts records. This tutorial builds that page against a SQL Server table using ADO.NET with parameters, so you can see every step instead of relying on a data source control.
The table
CREATE TABLE dbo.Contacts
(
ContactId int IDENTITY(1,1) PRIMARY KEY,
FullName nvarchar(100) NOT NULL,
Email nvarchar(200) NOT NULL,
City nvarchar(80) NULL
);
INSERT INTO dbo.Contacts (FullName, Email, City) VALUES
(N'Ana Ruiz', N'ana@example.org', N'Seville'),
(N'Tom Becker', N'tom@example.org', N'Hamburg');
Add the connection string to web.config:
<connectionStrings>
<add name="Db" providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Demo;Integrated Security=True" />
</connectionStrings>
The markup
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Contacts.aspx.cs" Inherits="Demo.Contacts" %>
<!DOCTYPE html>
<html>
<head runat="server"><title>Contacts</title></head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvContacts" runat="server" AutoGenerateColumns="false"
DataKeyNames="ContactId" ShowFooter="true"
OnRowEditing="gvContacts_RowEditing"
OnRowCancelingEdit="gvContacts_RowCancelingEdit"
OnRowUpdating="gvContacts_RowUpdating"
OnRowDeleting="gvContacts_RowDeleting"
OnRowCommand="gvContacts_RowCommand"
EmptyDataText="No contacts yet.">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate><%#: Eval("FullName") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Bind("FullName") %>' MaxLength="100" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtName"
ErrorMessage="Required" ValidationGroup="edit" Display="Dynamic" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewName" runat="server" MaxLength="100" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtNewName"
ErrorMessage="Required" ValidationGroup="add" Display="Dynamic" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="E-mail">
<ItemTemplate><%#: Eval("Email") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmail" runat="server" Text='<%# Bind("Email") %>' TextMode="Email" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewEmail" runat="server" TextMode="Email" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate><%#: Eval("City") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCity" runat="server" Text='<%# Bind("City") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewCity" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="Edit" Text="Edit" CausesValidation="false" />
<asp:LinkButton runat="server" CommandName="Delete" Text="Delete" CausesValidation="false"
OnClientClick="return confirm('Delete this contact?');" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton runat="server" CommandName="Update" Text="Save" ValidationGroup="edit" />
<asp:LinkButton runat="server" CommandName="Cancel" Text="Cancel" CausesValidation="false" />
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton runat="server" CommandName="AddNew" Text="Add" ValidationGroup="add" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblMessage" runat="server" />
</form>
</body>
</html>
Key points in the markup:
DataKeyNames="ContactId"keeps each row's primary key on the server, so you never need a hidden column for it.- The
CommandNamevaluesEdit,Update,CancelandDeleteare recognised by the GridView and raise the matching events.AddNewis our own name, so it only raisesRowCommand. <%#: … %>HTML-encodes the value (available since .NET 4.5), protecting the page against script stored in the data.- Separate validation groups stop the footer's validators from blocking a row update and vice versa.
The code-behind
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Demo
{
public partial class Contacts : Page
{
private static string ConnStr =>
ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
var table = new DataTable();
using (var con = new SqlConnection(ConnStr))
using (var da = new SqlDataAdapter(
"SELECT ContactId, FullName, Email, City FROM dbo.Contacts ORDER BY FullName", con))
{
da.Fill(table);
}
gvContacts.DataSource = table;
gvContacts.DataBind();
}
protected void gvContacts_RowEditing(object sender, GridViewEditEventArgs e)
{
gvContacts.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void gvContacts_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvContacts.EditIndex = -1;
BindGrid();
}
protected void gvContacts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int id = (int)gvContacts.DataKeys[e.RowIndex].Value;
GridViewRow row = gvContacts.Rows[e.RowIndex];
string name = ((TextBox)row.FindControl("txtName")).Text.Trim();
string email = ((TextBox)row.FindControl("txtEmail")).Text.Trim();
string city = ((TextBox)row.FindControl("txtCity")).Text.Trim();
Execute("UPDATE dbo.Contacts SET FullName = @name, Email = @email, City = @city WHERE ContactId = @id",
cmd =>
{
cmd.Parameters.Add("@name", SqlDbType.NVarChar, 100).Value = name;
cmd.Parameters.Add("@email", SqlDbType.NVarChar, 200).Value = email;
cmd.Parameters.Add("@city", SqlDbType.NVarChar, 80).Value =
city.Length == 0 ? (object)DBNull.Value : city;
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
});
gvContacts.EditIndex = -1;
BindGrid();
lblMessage.Text = "Contact updated.";
}
protected void gvContacts_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = (int)gvContacts.DataKeys[e.RowIndex].Value;
Execute("DELETE FROM dbo.Contacts WHERE ContactId = @id",
cmd => cmd.Parameters.Add("@id", SqlDbType.Int).Value = id);
BindGrid();
lblMessage.Text = "Contact deleted.";
}
protected void gvContacts_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName != "AddNew") return;
GridViewRow footer = gvContacts.FooterRow;
string name = ((TextBox)footer.FindControl("txtNewName")).Text.Trim();
string email = ((TextBox)footer.FindControl("txtNewEmail")).Text.Trim();
string city = ((TextBox)footer.FindControl("txtNewCity")).Text.Trim();
Execute("INSERT INTO dbo.Contacts (FullName, Email, City) VALUES (@name, @email, @city)",
cmd =>
{
cmd.Parameters.Add("@name", SqlDbType.NVarChar, 100).Value = name;
cmd.Parameters.Add("@email", SqlDbType.NVarChar, 200).Value = email;
cmd.Parameters.Add("@city", SqlDbType.NVarChar, 80).Value =
city.Length == 0 ? (object)DBNull.Value : city;
});
BindGrid();
lblMessage.Text = "Contact added.";
}
private static void Execute(string sql, Action<SqlCommand> addParameters)
{
using (var con = new SqlConnection(ConnStr))
using (var cmd = new SqlCommand(sql, con))
{
addParameters(cmd);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
}
What happens on each click
- Edit: the GridView raises
RowEditingwith the row index. SettingEditIndexand rebinding renders that row with itsEditItemTemplate. - Save: validators in group
editrun, thenRowUpdating. We read the boxes withFindControl, run the parameterisedUPDATE, leave edit mode and rebind. - Cancel:
RowCancelingEdit; resetEditIndexto -1. - Delete: the browser's
confirm()runs first; returningfalsecancels the postback. ThenRowDeletingdeletes by key. - Add: a custom command, so only
RowCommandfires. The footer's controls are read throughFooterRow.
If you handle RowUpdating or RowDeleting without a data source control, you must handle them; otherwise the GridView throws "The GridView fired event RowEditing which wasn't handled".
The empty-table problem
When the table has no rows, the GridView shows EmptyDataText and does not render the footer, so there is no way to add the first contact. Two common fixes: put the insert form outside the grid (as in the form-based CRUD example), or add an EmptyDataTemplate containing the same input boxes and an Add button, and read them from gvContacts.Controls[0].Controls[0] in RowCommand.
Going further
- Paging: set
AllowPaging="true", handlePageIndexChanging, setPageIndexand rebind. Keeping check boxes across pages is covered in this article. - Concurrency: include a
rowversioncolumn in theWHEREclause of the update to detect edits made by someone else meanwhile. - Exporting the grid: export to Word, Excel, text or PDF.
Two related tutorials stay on their own pages because readers arrive at them directly: editing GridView data through a separate form and exporting a GridView to Word, Excel, text or PDF.
Checklist for list pages
- Bind in
Page_Loadonly when!IsPostBack, and rebind after every change (paging, sorting, saving). - Keys go in
DataKeyNamesordata-*attributes; never parse cell text to find a record. - Every command (Delete, Update, a ticked-rows action) re-checks permissions on the server: hidden buttons and disabled boxes are not security.
- Large tables are paged in SQL (
OFFSET … FETCH) rather than loading every row and letting the control page in memory. - Visual states (selected, ticked, hover) are CSS classes, so they also print and can be tested.
Sources
- Microsoft Learn: Repeater class, Repeater.ItemDataBound, Repeater.ItemCommand, Strongly typed data controls and model binding, PagedDataSource, DataPager, ListView, GridView.SelectedRow, GridView.SelectedDataKey, GridView.RowCommand, CheckBox class, GridView.DataKeys, GridView.PageIndexChanging, GridView.RowDataBound, Control.ViewState, HiddenField class, GridView.UseAccessibleHeader, TableRow.TableSection, GridView class, GridView.RowUpdating, GridView.DataKeyNames, An overview of inserting, updating and deleting data, ADO.NET overview, SqlCommand.ExecuteNonQuery.
- MDN: HTMLInputElement.indeterminate, Using data attributes, :has(), :checked, :hover, :nth-child(), :focus-within, Content Security Policy, Window.print(), Printing (CSS), break-inside.
- jQuery API: .prop(), :checked selector, .on(), .closest(), .data(), .toggleClass(), .trigger(), mouseenter event.