ASP.NET Gridview control
- The GridView control is a feature rich and versatile control used to accept, display, and edit data on a web page
- We use Gridview when we have to show data in table format and also have to perform quick actions like update, delete
Advantages of - ASP.NET Gridview control
- Built-in update and delete capabilities.
- Built-in paging capabilities.
- Built-in row selection capabilities.
- Programmatic access to the GridView object model to dynamically set properties, handle events, and so on.
- Customizable appearance through themes and styles.
Example :
Frond-End code
<form id="form1" runat="server">
<h2 style="text-align:center">Gridview Example - insert,update,delete</h2>
<asp:GridView ID="gvdata" runat="server" AutoGenerateColumns="false" DataKeyNames="Srno"
OnRowEditing="gvdata_RowEditing" OnRowCancelingEdit="gvdata_RowCancelingEdit"
OnRowUpdating="gvdata_RowUpdating" OnRowDeleting="gvdata_RowDeleting" EmptyDataText="No data found">
<Columns>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txteName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("City") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txteCountry" runat="server" Text='<%# Eval("City") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true"
ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
<tr>
<td style="width: 150px">
Name:<br />
<asp:TextBox ID="txtname" runat="server" Width="140" />
</td>
<td style="width: 150px">
City:<br />
<asp:TextBox ID="txtcity" runat="server" Width="140" />
</td>
<td style="width: 100px">
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
</td>
</tr>
</table>
</form>
Back-End code
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Training
{
public partial class gridviewexample : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
gvdata.DataSource = getdata();
gvdata.DataBind();
}
}
protected void gvdata_RowEditing(object sender, GridViewEditEventArgs e)
{
gvdata.EditIndex = e.NewEditIndex;
gvdata.DataSource = getdata();
gvdata.DataBind();
}
protected void gvdata_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvdata.EditIndex = -1;
gvdata.DataSource = getdata();
gvdata.DataBind();
}
protected void gvdata_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
con.Close();
GridViewRow row = gvdata.Rows[e.RowIndex];
string name = (row.FindControl("txteName") as TextBox).Text;
string city = (row.FindControl("txteCountry") as TextBox).Text;
SqlCommand cmd = new SqlCommand("Update GVDemo set Name='" + name + "',City='" + city + "' where Srno='" + gvdata.DataKeys[e.RowIndex].Value + "'", con);
cmd.Parameters.AddWithValue("@Date", DateTime.Today.ToShortDateString());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
gvdata.EditIndex = -1;
gvdata.DataSource = getdata();
gvdata.DataBind();
string message = "Data Updated Successfully,Thank you!";
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += Request.Url.AbsoluteUri;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
}
catch (Exception es)
{
}
}
protected void gvdata_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
con.Close();
GridViewRow row = gvdata.Rows[e.RowIndex];
SqlCommand cmd = new SqlCommand("Delete from GVDemo where Srno='" + gvdata.DataKeys[e.RowIndex].Value + "'", con);
cmd.Parameters.AddWithValue("@Date", DateTime.Today.ToShortDateString());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
gvdata.EditIndex = -1;
gvdata.DataSource = getdata();
gvdata.DataBind();
string message = " Data Deleted Successfully,Thank you!";
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += Request.Url.AbsoluteUri;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
}
protected void btnAdd_Click(object sender, EventArgs e)
{
con.Close();
SqlCommand cmd = new SqlCommand("insert into GVDemo values ('"+txtname.Text+"','"+txtcity.Text+"')",con);
con.Open();
cmd.ExecuteNonQuery();
gvdata.DataSource = getdata();
gvdata.DataBind();
txtname.Text = "";
txtcity.Text = "";
}
protected DataSet getdata()
{
con.Close();
SqlCommand cmd = new SqlCommand("select * from GVDemo order by Srno ASC", con);
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
con.Close();
return ds;
}
}
}