Insert, edit, update and delete records with a form and a GridView in ASP.NET (C#)
Editing inside the grid is compact, but many business screens are easier to use with a form: the user fills in fields above, the list below shows what is stored, and clicking a row loads it back into the form. This example builds that screen with a GridView, a few text boxes and four buttons.

Database and configuration
The page uses the same dbo.Contacts table and Db connection string as the inline GridView example:
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
);
The page
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ContactForm.aspx.cs" Inherits="Demo.ContactForm" %>
<!DOCTYPE html>
<html>
<head runat="server"><title>Contacts</title></head>
<body>
<form id="form1" runat="server">
<asp:HiddenField ID="hfId" runat="server" />
<p>
<asp:Label runat="server" AssociatedControlID="txtName" Text="Name" />
<asp:TextBox ID="txtName" runat="server" MaxLength="100" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtName" ErrorMessage="Name is required" Display="Dynamic" />
</p>
<p>
<asp:Label runat="server" AssociatedControlID="txtEmail" Text="E-mail" />
<asp:TextBox ID="txtEmail" runat="server" TextMode="Email" MaxLength="200" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtEmail" ErrorMessage="E-mail is required" Display="Dynamic" />
</p>
<p>
<asp:Label runat="server" AssociatedControlID="txtCity" Text="City" />
<asp:TextBox ID="txtCity" runat="server" MaxLength="80" />
</p>
<p>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" Enabled="false" />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" Enabled="false"
CausesValidation="false" OnClientClick="return confirm('Delete this contact?');" />
<asp:Button ID="btnClear" runat="server" Text="Clear" OnClick="btnClear_Click" CausesValidation="false" />
</p>
<asp:Label ID="lblMessage" runat="server" />
<asp:GridView ID="gvContacts" runat="server" AutoGenerateColumns="false" DataKeyNames="ContactId"
OnSelectedIndexChanged="gvContacts_SelectedIndexChanged" EmptyDataText="No contacts yet.">
<Columns>
<asp:ButtonField CommandName="Select" Text="Select" CausesValidation="false" />
<asp:BoundField DataField="FullName" HeaderText="Name" HtmlEncode="true" />
<asp:BoundField DataField="Email" HeaderText="E-mail" HtmlEncode="true" />
<asp:BoundField DataField="City" HeaderText="City" HtmlEncode="true" NullDisplayText="-" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
The code-behind
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
namespace Demo
{
public partial class ContactForm : 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_SelectedIndexChanged(object sender, EventArgs e)
{
int id = (int)gvContacts.SelectedDataKey.Value;
using (var con = new SqlConnection(ConnStr))
using (var cmd = new SqlCommand(
"SELECT FullName, Email, City FROM dbo.Contacts WHERE ContactId = @id", con))
{
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
con.Open();
using (SqlDataReader r = cmd.ExecuteReader())
{
if (!r.Read()) { ShowMessage("That contact no longer exists."); ResetForm(); BindGrid(); return; }
hfId.Value = id.ToString();
txtName.Text = r.GetString(0);
txtEmail.Text = r.GetString(1);
txtCity.Text = r.IsDBNull(2) ? "" : r.GetString(2);
}
}
SetEditMode(true);
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (!IsValid) return;
Save("INSERT INTO dbo.Contacts (FullName, Email, City) VALUES (@name, @email, @city)", null);
ShowMessage("Contact added.");
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
if (!IsValid || !int.TryParse(hfId.Value, out int id)) return;
Save("UPDATE dbo.Contacts SET FullName = @name, Email = @email, City = @city WHERE ContactId = @id", id);
ShowMessage("Contact updated.");
}
protected void btnDelete_Click(object sender, EventArgs e)
{
if (!int.TryParse(hfId.Value, out int id)) return;
using (var con = new SqlConnection(ConnStr))
using (var cmd = new SqlCommand("DELETE FROM dbo.Contacts WHERE ContactId = @id", con))
{
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
con.Open();
cmd.ExecuteNonQuery();
}
ResetForm();
BindGrid();
ShowMessage("Contact deleted.");
}
protected void btnClear_Click(object sender, EventArgs e)
{
ResetForm();
lblMessage.Text = "";
}
private void Save(string sql, int? id)
{
using (var con = new SqlConnection(ConnStr))
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("@name", SqlDbType.NVarChar, 100).Value = txtName.Text.Trim();
cmd.Parameters.Add("@email", SqlDbType.NVarChar, 200).Value = txtEmail.Text.Trim();
string city = txtCity.Text.Trim();
cmd.Parameters.Add("@city", SqlDbType.NVarChar, 80).Value =
city.Length == 0 ? (object)DBNull.Value : city;
if (id.HasValue) cmd.Parameters.Add("@id", SqlDbType.Int).Value = id.Value;
con.Open();
cmd.ExecuteNonQuery();
}
ResetForm();
BindGrid();
}
private void ResetForm()
{
hfId.Value = "";
txtName.Text = txtEmail.Text = txtCity.Text = "";
gvContacts.SelectedIndex = -1;
SetEditMode(false);
}
private void SetEditMode(bool editing)
{
btnAdd.Enabled = !editing;
btnUpdate.Enabled = editing;
btnDelete.Enabled = editing;
}
private void ShowMessage(string text) => lblMessage.Text = text;
}
}
How it works
- Select. A
ButtonFieldwithCommandName="Select"sets the grid'sSelectedIndexand raisesSelectedIndexChanged.SelectedDataKeygives the primary key of that row thanks toDataKeyNames. The record is read again from the database rather than from the grid's cells, so the form shows current data. - Edit mode. The id is kept in a
HiddenField, and the buttons are enabled or disabled to match. Because disabled server buttons cannot raise events, a user cannot click Update with nothing selected. - Validation. Validators run in the browser, and
IsValidis checked again on the server because client-side checks can be bypassed. - Parameters. Every statement uses typed parameters; see SQL injection for why.
- Encoding.
BoundFieldHTML-encodes values by default; the attribute is written out here to make it visible.
The hidden field is under the user's control, like everything in the form. Here that is harmless, because any user of this page may edit any contact. If records belong to different users, check ownership in the WHERE clause of the update and delete.
Variations
- Use a
DetailsVieworFormViewfor the form if you prefer templates bound to the same data. - Read the data with a reader instead of an adapter: see binding a GridView with ExecuteReader.
- Read the selected row on the server without a database round trip: get the GridView selected row in code-behind.
Common problems
- The form keeps old values after Update.
ResetForm()is not called, or the grid is rebound inPage_Loadon every postback, which resetsSelectedIndexin an unexpected order. Bind only on the first request and after each change. - "Specified argument was out of the range" on
SelectedDataKey.DataKeyNamesis missing on the grid. - Validators block the Select link. Set
CausesValidation="false"on theButtonField, as in the markup above, otherwise an empty form prevents selecting a row. - Two users edit the same contact. The last save wins. Add a
rowversioncolumn, keep its value in a hidden field and include it in theWHEREclause to detect conflicts.
Official documentation
- Microsoft Learn: GridView.SelectedDataKey, ButtonField, HiddenField
- Microsoft Learn: SqlCommand class
- Microsoft Learn: Page.IsValid