Featured

ASP.NET Web Form GridView CRUD

Last modified: April 12, 2022

1. Create a ASP.NET Web Form application

project

project

project

project

2. SQL Server Managment Studio

  • Open SQL Server Managment Studio and run the below SQL Script to create a database, table and insert sample records
CREATE DATABASE GridView GO CREATE TABLE [GridView].[dbo].[Product]( [Id] [int] IDENTITY(1,1) NOT NULL, [Sku] [nvarchar](50) NOT NULL, [Name] [nvarchar](200) NOT NULL, [Manufacturer] [nvarchar](200) NOT NULL, [Price] [decimal](9, 2) NOT NULL, CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY] GO INSERT INTO [GridView].[dbo].[Product] (Sku,[Name], Manufacturer, Price) VALUES ('iphone12', 'iPhone 12', 'Apple', 800), ('iphone12pro', 'iPhone 12 Pro', 'Apple', 900), ('iphone13', 'iPhone 13', 'Apple', 1000), ('iphone12pro', 'iPhone 12 Pro', 'Apple', 1100)
  • Create a folder named Data
  • Add a new item
  • Select ADO.NET Entity Data Model

db

db

db

db

db

db

db

db

3. Create a GridView

  • Go to Default.aspx, delete it content and it should look like this
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server"> </asp:Content>
  • Add a Product GridView to Default.aspx page
    • DataKeyNames means unqiue key of the data
    • BoundField DataField maps to data column/property
<asp:GridView DataKeyNames="Id" ID="GridViewProduct" AutoGenerateColumns="False" runat="server"> <Columns> <asp:BoundField DataField="Sku" HeaderText="Sku" SortExpression="Sku" /> <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> <asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" SortExpression="Manufacturer" /> <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" /> </Columns> </asp:GridView>
  • Go to Default.aspx.cs, which is code behind of Go to Default.aspx web page. The C# code will be in this page.
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { UpdateProductGrid(); } } protected void UpdateProductGrid() { using (var db = new GridViewEntities()) { var products = db.Product.ToList(); GridViewProduct.DataSource = products; GridViewProduct.DataBind(); } }

-Now we have this gridview

4. GridView and Form (Add)

  • We create a form to add/update the product and style the GridView to Bootstrap table format.
  • We use AJAX component to refresh the GridView, to do that we need to make use of UpdatePanel
<asp:UpdatePanel ID="UpdatePanelProject" runat="server" UpdateMode="Conditional" > <ContentTemplate> ... </ContentTemplate> </asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanelProject" runat="server" UpdateMode="Conditional" > <ContentTemplate> <div> <h2><asp:Label ID="LabelTitle" runat="server" Text="Add Product" /></h2> <table> <tr> <td>Sku</td> <td> <asp:TextBox CssClass="form-control" ID="TextBoxSku" runat="server"></asp:TextBox> </td> </tr> <tr> <td>Name</td> <td> <asp:TextBox CssClass="form-control" ID="TextBoxName" runat="server"></asp:TextBox> </td> </tr> <tr> <td>Manufacturer</td> <td> <asp:TextBox CssClass="form-control" ID="TextBoxManufacturer" runat="server"></asp:TextBox> </td> </tr> <tr> <td>Price</td> <td> <asp:TextBox CssClass="form-control" ID="TextBoxPrice" runat="server"></asp:TextBox> </td> </tr> </table> <asp:HiddenField ID="ProductId" runat="server" /> <asp:Button ID="ButtonSubmit" CssClass="btn btn-primary" runat="server" Text="Add" OnClick="ButtonSubmit_Click" /> </div> <br /> <asp:GridView OnRowDeleting="GridViewProduct_RowDeleting" OnRowEditing="GridViewProduct_RowEditing" OnRowCancelingEdit="GridViewProduct_RowCancelingEdit" OnRowUpdating="GridViewProduct_RowUpdating" CssClass="table table-striped table-bordered table-hover" DataKeyNames="Id" ID="GridViewProduct" AutoGenerateColumns="False" runat="server"> <Columns> <asp:BoundField DataField="Sku" HeaderText="Sku" SortExpression="Sku" /> <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> <asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" SortExpression="Manufacturer" /> <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" /> <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" /> </Columns> </asp:GridView> </ContentTemplate> </asp:UpdatePanel>

4. Add a Product

protected void ButtonSubmit_Click(object sender, EventArgs e) { using(var db = new GridViewEntities()) { var product = new Product(); product.Sku = TextBoxSku.Text.Trim(); product.Manufacturer = TextBoxManufacturer.Text.Trim(); product.Name = TextBoxName.Text.Trim(); product.Price = decimal.Parse(TextBoxPrice.Text.Trim()); db.Product.Add(product); db.SaveChanges(); UpdateProductGrid(); UpdatePanelProject.Update(); //refresh the webpage via AJAX } }

5. Delete a Product

protected void GridViewProduct_RowDeleting(object sender, GridViewDeleteEventArgs e) { var id = (int)GridViewProduct.DataKeys[e.RowIndex].Value; //get the primary key using(var db = new GridViewEntities()) { var product = db.Product.Where(w => w.Id == id).FirstOrDefault(); db.Product.Remove(product); db.SaveChanges(); UpdateProductGrid(); UpdatePanelProject.Update(); } }

6. Enable/Disable Edit Function for Product

protected void GridViewProduct_RowEditing(object sender, GridViewEditEventArgs e) { GridViewProduct.EditIndex = e.NewEditIndex; UpdateProductGrid(); UpdatePanelProject.Update(); } protected void GridViewProduct_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridViewProduct.EditIndex = -1; UpdateProductGrid(); UpdatePanelProject.Update(); }

project

7. Edit a Product

protected void GridViewProduct_RowUpdating(object sender, GridViewUpdateEventArgs e) { var id = (int)GridViewProduct.DataKeys[e.RowIndex].Value; //get the primary key var row = (GridViewRow)GridViewProduct.Rows[e.RowIndex]; var TextBoxSku = (TextBox)row.Cells[0].Controls[0]; var TextBoxName = (TextBox)row.Cells[1].Controls[0]; var TextBoxManufacturer = (TextBox)row.Cells[2].Controls[0]; var TextBoxPrice = (TextBox)row.Cells[3].Controls[0]; GridViewProduct.EditIndex = -1; using(var db = new GridViewEntities()) { var product = db.Product.Where(w => w.Id == id).FirstOrDefault(); product.Sku = TextBoxSku.Text.Trim(); product.Manufacturer = TextBoxManufacturer.Text.Trim(); product.Name = TextBoxName.Text.Trim(); product.Price = decimal.Parse(TextBoxPrice.Text.Trim()); db.SaveChanges(); UpdateProductGrid(); UpdatePanelProject.Update(); } }