Home » ASP.Net, GridView Tips, Tech Corner

Edit,Update,Cancel In a GridView

26 March 2009 1 comment Posted By:Lloyd

I am posting this one with a notion that the readers do have a little bit knowledge about dot net.Hope it helps.

Pre-requisites
Add a gridview(gdvw_Sample) to your ‘Default.aspx’ page,

  • Bind the gridview with values from a table in the database.
  • Remove “AutoGenerate Columns” of gridview.
  • Add two “boundfields”.
  • Set the primary key of the table as the “datakey” of the gridview.
  • Add a “command field-Edit Update Cancel”.

How to set the datakey and BoundFields???
Copying the Html code below will create a gridview with 2 boundfields Name ,Address and datakey as Id.

<asp:GridView ID=”gdvw_Sample” runat=”server” AutoGenerateColumns=”False”
DataKeyNames=”Id” onrowcancelingedit=”gdvw_Sample_RowCancelingEdit”
onrowediting=”gdvw_Sample_RowEditing” onrowupdating=”gdvw_Sample_RowUpdating”>
<Columns>
<asp:BoundField DataField=”Name” HeaderText=”Name” />
<asp:BoundField DataField=”Address” HeaderText=”Address” />
<asp:CommandField ShowEditButton=”True” />
</Columns>
</asp:GridView>

  • BoundFields can be set directly from the design also ,by “edit columns” of the gridview(taken from top right corner of the gridview itself).
  • Datakeys can be set from the “property”>> “DataKeyNames”.

“default.aspx.cs”
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;

public partial class _Default : System.Web.UI.Page
{
DBAccess dbobj = new DBAccess();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindgridview();
}
}
protected void gdvw_Sample_RowEditing(object sender, GridViewEditEventArgs e)
{
gdvw_Sample.EditIndex = e.NewEditIndex;
bindgridview();
}

private void bindgridview()
{
dbobj.GetTable(”select * from Student”);
gdvw_Sample.DataSource = dbobj.dt;
gdvw_Sample.DataBind();
}
protected void gdvw_Sample_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gdvw_Sample.EditIndex = -1;
bindgridview();
}
protected void gdvw_Sample_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string t1 = ((TextBox)(gdvw_Sample.Rows[e.RowIndex].Cells[0].Controls[0])).Text.ToString();
string t2 = ((TextBox)(gdvw_Sample.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString();
string id = gdvw_Sample.DataKeys[e.RowIndex].Value.ToString();
dbobj.ExecuteQuery(”update Student set Name=’”+t1+”‘,Address=’”+t2+”‘where Id=’”+id+”‘”);
gdvw_Sample.EditIndex = -1;
bindgridview();
}
}

Notes:
1) The method “bindgridview()” is used to bind the grid with values from a table.
2) “DBAccess” is a class wrote for accessing database.

To add this class,

Solution Explorer >>Rightclick on the website name>>Add newItem>>From the new window that opens,select CLASS,name it “DBAccess.cs”>>Paste the entire code below.

“DBAccess.cs”

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.Common;
using System.Web.Configuration;

public class DBAccess
{
public SqlConnection sqlCon = new SqlConnection();
public SqlCommand sqlCmd = new SqlCommand();
public SqlDataAdapter sqlDa = new SqlDataAdapter();
public DataTable dt;

public DBAccess()
{
sqlCon.ConnectionString = “server=.;uid=sa;pwd=admin;database=test”;
}

private SqlConnection GetConnection()
{
try
{
if (sqlCon.State == ConnectionState.Open)
{ sqlCon.Close(); }
sqlCon.Open();
}
catch (Exception ex)
{ sqlCon.Close(); }
return sqlCon;
}

public DataTable GetTable(string sql)
{
try
{
sqlCmd.Connection = GetConnection();
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = sql;
sqlDa.SelectCommand = sqlCmd;
dt = new DataTable();
sqlDa.Fill(dt);
if (sqlCon.State == ConnectionState.Open)
{ sqlCon.Close(); }
}
catch (Exception ex)
{
if (sqlCon.State == ConnectionState.Open)
{ sqlCon.Close(); }
}
return dt;
}

public int ExecuteQuery(string sql)
{
int rslt = 0;
try
{
sqlCmd.Connection = GetConnection();
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = sql;
rslt = sqlCmd.ExecuteNonQuery();
if (sqlCon.State == ConnectionState.Open)
{ sqlCon.Close(); }
}
catch (Exception ex)
{
if (sqlCon.State == ConnectionState.Open)
{ sqlCon.Close(); }
}
return rslt;
}
}

Notes:
1) Don’t forget to edit the connection string in the constructor portion of the “DBAccess.cs” and also the database name,uid and password of sqlserver.

The Table design for the the table used above “Student”

Id int
Name varchar(50)
Address varchar(50)

Related posts:

  1. Filling Gridview without using database
  2. Dropdownlist inside a Gridview
  3. How to Bind Images from Database in a GridView
  4. XML serialization of Objects in .NET
  5. Convert a String in CSV format to INT Array in .NET

One Comment »

  • praveen said:

    I am apply for ur coding. It is working well. thank u for ur information.
    by
    praveen kumar.s

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host 'mysql.three2tango.com' (1) in /home/content/s/h/a/shadihameed/html/www.three2tango.com/wp-content/themes/arthemia/footer.php on line 38
Could not connect