ASP.NET

Insert, edit, update and delete records with a form and a GridView in ASP.NET (C#)

ASP.NET · · Published 2026-10-21

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.

Diagram of the page: a form with Name, E-mail and City fields and Add, Update, Delete and Clear buttons above a grid of saved records with a Select link on each row
Layout of the page built in this tutorial: the form on top, the grid of records below.

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

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

Common problems

Official documentation