How to create custom editing on grid view in Asp.net
How to create custom editing on grid view in Asp.net.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Akkiraju IvaturiPosted Sep 7, 2012, 6:48 PM
ASP.NET Code:
<%@ page autoeventwireup="true" codefile="MyExample.aspx.cs" inherits="GridView_MyExample"
language="C#" masterpagefile="~/MasterPages/Default.master" title="GridView: MY example" %>
autogeneratecolumns="False" datakeynames="ShipperID" emptydatatext="There are no data records to display."
onpageindexchanging="gvShippers_PageIndexChanging" onrowcancelingedit="gvShippers_RowCancelingEdit"
onrowcommand="gvShippers_RowCommand" onrowdeleting="gvShippers_RowDeleting" onrowediting="gvShippers_RowEditing"
onrowupdating="gvShippers_RowUpdating" onsorting="gvShippers_Sorting" showfooter="true"
style="margin-top: 20px;">
readonly="true" sortexpression="ShipperID" />
<%# Eval("CompanyName") %>
<%# Eval("Phone") %>
Code Behind file:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class GridView_MyExample : System.Web.UI.Page
{
private string Sort
{
get
{
return String.Concat(
this.SortExpression,
(this.SortDirection == SortDirection.Ascending) ? " ASC" : " DESC");
}
}
private SortDirection SortDirection
{
get
{
if (ViewState["SortDirection"] == null)
{
ViewState["SortDirection"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["SortDirection"];
}
set { ViewState["SortDirection"] = value; }
}
private string SortExpression
{
get
{
if (ViewState["SortExpression"] == null)
{
ViewState["SortExpression"] = "ShipperID";
}
return ViewState["SortExpression"].ToString();
}
set { ViewState["SortExpression"] = value; }
}
private IDictionary GetValues(GridViewRow row)
{
IOrderedDictionary dictionary = new OrderedDictionary();
foreach (Control control in row.Controls)
{
DataControlFieldCell cell = control as DataControlFieldCell;
if ((cell != null) && cell.Visible)
{
cell.ContainingField.ExtractValuesFromCell(dictionary, cell, row.RowState, true);
}
}
IDictionary values = new Dictionary();
foreach (DictionaryEntry de in dictionary)
{
values[de.Key.ToString()] = de.Value;
}
return values;
}
private void SetData()
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("SELECT * FROM [Shippers]", conn))
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
try
{
conn.Open();
DataTable dt = new DataTable();
adapter.Fill(dt);
DataView dv = dt.DefaultView;
dv.Sort = this.Sort;
gvShippers.DataSource = dv;
gvShippers.DataBind();
}
catch{}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.SetData();
}
}
protected void gvShippers_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvShippers.PageIndex = e.NewPageIndex;
this.SetData();
}
protected void gvShippers_Sorting(object sender, GridViewSortEventArgs e)
{
if (this.SortExpression.Equals(e.SortExpression))
{
this.SortDirection = (this.SortDirection == SortDirection.Ascending)
? SortDirection.Descending
: SortDirection.Ascending;
}
else
{
this.SortDirection = SortDirection.Ascending;
}
this.SortExpression = e.SortExpression;
this.SetData();
}
protected void gvShippers_RowEditing(object sender, GridViewEditEventArgs e)
{
gvShippers.EditIndex = e.NewEditIndex;
this.SetData();
}
protected void gvShippers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvShippers.EditIndex = -1;
this.SetData();
}
protected void gvShippers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvShippers.Rows[e.RowIndex];
var newValues = this.GetValues(row);
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("UPDATE [Shippers] SET [CompanyName] = @CompanyName, [Phone] = @Phone WHERE (ShipperID = @ShipperID)", conn))
{
cmd.Parameters.AddWithValue("ShipperID", gvShippers.DataKeys[row.RowIndex]["ShipperID"]);
cmd.Parameters.AddWithValue("CompanyName", newValues["CompanyName"]);
cmd.Parameters.AddWithValue("Phone", newValues["Phone"]);
try
{
conn.Open();
if (cmd.ExecuteNonQuery().Equals(1))
{
lblMessage.Text = String.Format(
"Shipper '{0}' successfully updated.",
cmd.Parameters["ShipperID"].Value);
gvShippers.EditIndex = -1;
this.SetData();
}
}
catch {}
}
}
protected void gvShippers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("DELETE FROM [Shippers] WHERE (ShipperID = @ShipperID)", conn))
{
cmd.Parameters.AddWithValue("ShipperID", gvShippers.DataKeys[e.RowIndex]["ShipperID"]);
try
{
conn.Open();
if (cmd.ExecuteNonQuery().Equals(1))
{
lblMessage.Text = String.Format(
"Shipper '{0}' successfully deleted.",
cmd.Parameters["ShipperID"].Value);
this.SetData();
}
}
catch {}
}
}
protected void gvShippers_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
LinkButton btnInsert = e.CommandSource as LinkButton;
if (btnInsert == null) { return; }
GridViewRow row = btnInsert.NamingContainer as GridViewRow;
TextBox txtCompanyName = row.FindControl("txtCompanyName") as TextBox;
TextBox txtPhone = row.FindControl("txtPhone") as TextBox;
if (txtCompanyName == null) { return; }
if (txtPhone == null) { return; }
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("INSERT INTO [Shippers] ([CompanyName], [Phone]) VALUES (@CompanyName, @Phone); SELECT @ShipperID = SCOPE_IDENTITY()", conn))
{
cmd.Parameters.AddWithValue("CompanyName", txtCompanyName.Text);
cmd.Parameters.AddWithValue("Phone", txtPhone.Text);
cmd.Parameters.Add("ShipperID", SqlDbType.Int);
cmd.Parameters["ShipperID"].Direction = ParameterDirection.Output;
try
{
conn.Open();
if (cmd.ExecuteNonQuery().Equals(1))
{
lblMessage.Text = String.Format(
"Shipper '{0}' successfully added.",
cmd.Parameters["ShipperID"].Value);
this.SetData();
}
}
catch {}
}
}
}
}
Satyapriya NayakPosted Sep 7, 2012, 1:42 PM
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
//SqlConnection conn = new SqlConnection(connStr);
SqlDataAdapter ad = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
DataTable dataTable;
SqlDataAdapter sqlda;
DataSet ds;
string str;
protected void Page_Load(object sender, EventArgs e)
{
Session["sortBy"] = null;
if (!IsPostBack)
{
FillVendorGrid();
}
}
private void FillVendorGrid()
{
SqlConnection conn = new SqlConnection(connStr);
dataTable = new DataTable();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM Vendor";
ad = new SqlDataAdapter(cmd);
ad.Fill(dataTable);
ResultGridView.DataSource = dataTable;
ResultGridView.DataBind();
}
protected void ResultGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
ResultGridView.EditIndex = e.NewEditIndex;
FillVendorGrid();
}
protected void ResultGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
ResultGridView.PageIndex = e.NewPageIndex;
FillVendorGrid();
}
protected void ResultGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SqlConnection conn = new SqlConnection(connStr);
cmd.Connection = conn;
cmd.CommandText = "DELETE FROM Vendor WHERE VendorId='" + ResultGridView.DataKeys[e.RowIndex].Values[0].ToString() + "'";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
FillVendorGrid();
}
protected void ResultGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtFName = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtFName");
TextBox txtLName = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtLName");
TextBox txtCity = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtCity");
TextBox txtState = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtState");
TextBox txtCountry = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtCountry");
TextBox txtDescription = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtDescription");
SqlConnection conn = new SqlConnection(connStr);
cmd.Connection = conn;
cmd.CommandText = "UPDATE Vendor SET VendorFName ='" + txtFName.Text + "',VendorLName ='" + txtLName.Text + "',VendorCity ='" + txtCity.Text + "',VendorState ='" + txtState.Text + "',VendorCountry ='" + txtCountry.Text + "',VendorDescription ='" + txtDescription.Text + "' WHERE VendorId='" + ResultGridView.DataKeys[e.RowIndex].Values[0].ToString() + "'";
conn.Open();
cmd.ExecuteNonQuery();
ResultGridView.EditIndex = -1;
FillVendorGrid();
conn.Close();
}
protected void ResultGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
ResultGridView.EditIndex = -1;
FillVendorGrid();
}
protected void ResultGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtFName = (TextBox)ResultGridView.FooterRow.FindControl("txtFName1");
TextBox txtLName = (TextBox)ResultGridView.FooterRow.FindControl("txtLName1");
TextBox txtCity = (TextBox)ResultGridView.FooterRow.FindControl("txtCity1");
TextBox txtState = (TextBox)ResultGridView.FooterRow.FindControl("txtState1");
TextBox txtCountry = (TextBox)ResultGridView.FooterRow.FindControl("txtCountry1");
TextBox txtDescription = (TextBox)ResultGridView.FooterRow.FindControl("txtDescription1");
SqlConnection conn = new SqlConnection(connStr);
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Vendor(VendorFName, VendorLName,VendorCity,VendorState,VendorCountry,VendorDescription) Values('" + txtFName.Text + "', '" + txtLName.Text + "', '" + txtCity.Text + "', '" + txtState.Text + "', '" + txtCountry.Text + "' , '" + txtDescription.Text + "')";
conn.Open();
cmd.ExecuteNonQuery();
FillVendorGrid();
conn.Close();
}
}
protected void btn_search_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
str = "select * from Vendor where VendorFName like '" + TextBox1.Text + "%'";
cmd = new SqlCommand(str, conn);
sqlda = new SqlDataAdapter(cmd);
ds = new DataSet();
sqlda.Fill(ds, "Vendor");
conn.Close();
ResultGridView.DataSource = ds;
ResultGridView.DataMember = "Vendor";
ResultGridView.DataBind();
}
protected void ResultGridView_Sorting(object sender, GridViewSortEventArgs e)
{
Session["sortBy"] = e.SortExpression;
FillVendorGrid();
}
}
Thanks
If this post helps you mark it as answer
Sukesh MarlaPosted Sep 7, 2012, 1:02 PM
Check this link
http://www.codeproject.com/Articles/18136/Edit-Individual-GridView-Cells-in-ASP-NET
Check this is correct answer if it helped.