GridView – Rich Data Control – This is a very flexible Grid Control, which is used when we want to render our data as tables through Rows / Columns. There are many extra Ordinary features included in this control, due to which we can also do Selection, Paging, Sorting, and Editing of the records being displayed. we can also extend its functionality by using Templates with GridView Control.
The main feature of GridView Control as compared to DataGrid Control is that we can use it even without writing a Program Logic Code without a single line and can render Stored Data through it in Underlying Database or any other collection.When we use GridView Control, we do not have to write any code for common tasks like Paging and Selection. While using DataGrid Control, we have to create Event Handlers to perform these common tasks. That’s GridView is very popular in the developer community.
In this asp .net post we describe How to perform insert update delete using grid view in asp .net with ADO .Net?.I have written this Post is especially For Beginners who want to learn the coding step by step.
In this tutorial, we will create a Gridview In which we perform insert, update, delete, edit operation. i want to delete the record from Gridview by click on the delete button but I want to show an alert message “Are you sure want to delete?” to achieve all these task have used Gridview.Read More
To start with Gridview operation we need a database. So that I have created a database table named “Teachers“with Id, Name, Salary.
Table Script
paste
CREATE TABLE [dbo].[Teachers](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](150) NULL,
[Address] [nvarchar](500) NULL,
[Salary] [decimal](18, 2) NULL,
CONSTRAINT [PK_Employee_1] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
) ON [PRIMARY]
Step 1-Now Let’s Start,Open Visual studio and add empty website.
Step2-Now add a gridview to the page
Step 3-Right-click on gridview and then click on gridview property and double click on the following event of gridview. We will perform an operation on those events.
Step 4 –Some gridview view event which are very useful.
1) Onrowcancelingedit
The RowCancelingEdit event is occur when the Cancel button of a row in edit mode is clicked
2) Onrowediting
The RowEditing event is fire when a row’s Edit button is clicked, but before the GridView control enters edit mode.
3) Onrowupdating
The RowUpdating event is fire when a row’s Update button is clicked, but before the GridView control updates the row
5) Onrowdeleting
The RowDeleting event is fire when a row’s Delete button is clicked, but before the GridView control deletes the row.
6)OnRowCommand
The RowCommand event is fire when a button is clicked in the GridView control.
Now event are created on codebehind of page.Now aspx page should be like this:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="Index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowCommand="GridView1_RowCommand" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
</asp:GridView>
</div>
</form>
</body>
</html>
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
}
Now paste the following code between gridview view tag.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="Index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Id,Name" AutoGenerateColumns="False" ShowFooter="True" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowCommand="GridView1_RowCommand" OnRowUpdating="GridView1_RowUpdating" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Action">
<EditItemTemplate>
<asp:Button ID="btnUpdate" CommandName="Update" runat="server" ToolTip="Update" Height="30px" Width="60px" Text="Update" />
<asp:Button ID="btnCancel" CommandName="Cancel" runat="server" Text="Cancel" ToolTip="Cancel" Height="30px" Width="60px" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" CommandName="Edit" Text="Edit" ToolTip="Edit" Height="30px" Width="60px" />
<asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" ToolTip="Delete" Height="30px" Width="60px" OnClientClick="return confirm('Are you sure you want to delete this ?');" />
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="AddNew" CommandName="AddNew" Width="120px" Height="30px" ToolTip="Add new User" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:Label ID="lbleditName" runat="server" Text='<%#Eval("Name") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblitemName" runat="server" Text='<%#Eval("Name") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrname" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary">
<EditItemTemplate>
<asp:TextBox ID="txtSalary" runat="server" Text='<%#Eval("Salary") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblSalary" runat="server" Text='<%#Eval("Salary") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrSalary" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<EditItemTemplate>
<asp:TextBox ID="txtAddress" runat="server" Text='<%#Eval("Address") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblAddress" runat="server" Text='<%#Eval("Address") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrAddress" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</div>
</form>
</body>
</html>
Eval function is used to bind data from database to controls inside DataBound controls like GridView, Repeater, etc.
Now Gridview should look like this
Now paste the below code for operation on the event of gridview.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Index : System.Web.UI.Page
{
//Replace you connection strings
SqlConnection con = new SqlConnection("Data Source=SQLEXPRESS01;Initial Catalog=DemoDataBase;User ID=sa;Password=ap@1234");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataGridView();
//Check page is loaded first time or it's loaded due to button on page
}
}
public void BindDataGridView()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Teachers", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow()); // if record not found then returning a blank table structure
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1; //after cancel button want go to one index back that's y -1
BindDataGridView();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex; //this open new index that is edit mode
BindDataGridView();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["Id"].ToString()); //finding Datakeynames from gridview
string Name = GridView1.DataKeys[e.RowIndex].Values["Name"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Teachers where Id=" + Id, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindDataGridView();
Response.Write("<script language=javascript>alert('" + Name + "'+'details deleted successfully');</script>");
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtUsrname = (TextBox)GridView1.FooterRow.FindControl("txtftrname");
TextBox txtsalary = (TextBox)GridView1.FooterRow.FindControl("txtftrSalary"); //find textbox control on footer with crrosponding id
TextBox txtadress = (TextBox)GridView1.FooterRow.FindControl("txtftrAddress");
con.Open();
SqlCommand cmd = new SqlCommand("insert into Teachers(Name,Salary,Address) values('" + txtUsrname.Text + "','" + txtsalary.Text + "','" + txtadress.Text + "')", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindDataGridView();
Response.Write("<script language=javascript>alert('" + txtUsrname.Text + "'+'Details inserted successfully');</script>");
}
else
{
Response.Write("<script language=javascript>alert('" + txtUsrname.Text + "'+' Details not inserted');</script>");
}
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
string Name = GridView1.DataKeys[e.RowIndex].Values["Name"].ToString();
TextBox txtSalary = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSalary");
TextBox txtAddress = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAddress");
con.Open();
SqlCommand cmd = new SqlCommand("update Teachers set Salary='" + txtSalary.Text + "',Address='" + txtAddress.Text + "' where Id=" + userid, con);
cmd.ExecuteNonQuery();
con.Close();
Response.Write("<script language=javascript>alert('" + Name + "'+' Details Updated successfully!');</script>");
GridView1.EditIndex = -1;
BindDataGridView();
}
}
IsPostBack is a property of the Asp.Net page that checks whether the page is loaded first time
or it is loaded due to button on page.Now run your code and perform gridview operation.
Downlaod Source Code
Reseult:
The post Simple Way To Insert ,Update and Delete in Gridview-Asp.Net appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- Gridview insert delete with custom objects in viewstate
- Multiple foreign keys to same table with cascade update and delete
- Delete and update with stored procedure in ormlite (SQL Server) & C#
- Remove and delete all cookies of my ASP NET c-sharp application
- How can I update a row and insert a new one automatically in NHibernate with one call to Save?
- Update or refresh Listview in Windows Phone 8.1 app with C# and XAML
- How to update image with JavaScript and ASP.NET MVC?
- Entity framework terms used with asp net mvc app
- Return id of record when insert or update or delete record
- WPF TextBox Binding does not update with Drag and Drop
- How can I scan an entire drive and delete all files (read-only or not) with multiple specific file extension?
- linq to sql dynamic data modify object before insert and update
- How to insert a variable into a long string with multiple quotation marks and escape characters?
- How to fetch data in background and update UI with the data asynchronously when ready?
- Insert and Delete statement using TOP 1
- Make a list with no formatting in ASP and C#
- `Attaching an entity of type failed...` exception while trying to update a class in EF and with a generic repository
- ASP Net Text box with Google like dropdown search values
- How to test ASP NET ashx Handler With File Attached
- Multiple Sql Insert String And RollBack With Catch(Exception)
- GridView and DetailsView Code Behind to Update DetailsView
- How to return a json string with content type json in net 6 and minimal api?
- Implement two authentication options (Token and Certificate) in ASP Net Core
- Blazor wasm, net core hosted, with authentication, relationships between applicationuser and my models in the shared project
- How to get data from third party rest API in MVC 6.0 and asp net core application
- How to insert cyrillic and other special chars to SQL Server with SqlCommand c#?
- Gridview with fixed header and full page width grid
- How to delete files saved on the server after sending and email with SMTP client in MVC application
- Different number results in Update and Delete messages
- Solution for INSERT or UPDATE and fetching newly created id on SQL server
- High memory allocations when using protobuf-net over json.net
- using the ASP.NET Caching API via method annotations in C#
- Disabling or removing the close button from uwp app
- XmlReader/Writer gives errors with end elements
- How to spawn a new Process to invoke a .net core console application?
- Unity - Add call back to GameObject OnMouseDown Event
- I confuse with datatimepickers and datetimes. Need some help
- Unity3d Swipe jump is not very responsive
- How to communicate from python script to C# exposed interface?
- Unable to put calendar selected date into datetime C#
- Rx - pause Observable.Interval
- Trycatching invoking of the UI thread
- How to open or run unknown file converted into byte[]
- What is the C# data type that allows complex and imaginary numbers?
- Document Design for Azure Search
- how to call C# web service with Serialization object from client
- Is it wrong to set ListBox DataSource property to null in order to change list Items?
- Loop on GetFields and GetProperties of a Type?
- Is it possible to declare multiple routes for ASPNET.Core OData
- C# WPF Add border to Image on Click event