Basic Gridview CRUD operations

Hi All,

This is very basic Gridview CRUD operations  :

take one Gridview name : GridView1

GridView1 properties  : If want to allow paging , sorting ,autogeneratedcolumn ,autogenerateddeletebutton ,edit make it trueas per your need but rather its not mandatory.

Go to events :

Generate the events just by double-click on that event. for e.g GridView1_RowEditing.

it will generate the

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//  GridView1.EditIndex = e.NewEditIndex;
// MyData();
}

where we need to write a code.

Steps:

Import
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

Initialize the imp variables

private SqlConnection con;
private SqlCommand cmd;
private SqlDataAdapter ad;
private DataTable dt;
string constring = ConfigurationManager.ConnectionStrings[“testConnectionString”].ToString();
con = new SqlConnection(constring);

//for binding data to gridview

private void MyData()
{

con.Open();
ad = new SqlDataAdapter(“select * from Employee”, con);

dt = new DataTable();
ad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();

con.Close();

}

//for working that edit button you need to create an RowEditing event .

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
MyData();
}

//for updating that row and refelecting data into database

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Accessing Edited values from the GridView
con.Open();
string EmpName = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string EmpAddress = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
cmd = new SqlCommand(“Update Employee set EmpAddress='” + EmpAddress + “‘ where EmpName='” + EmpName + “‘”, con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;

MyData(); // Rebind GridView to reflect changes made

}

//for canceling the edit we need to set the EditIndex to -1 otherwise it’ll fire an error.
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
MyData();
}

———————————————————————————————————————————————————————–

//Full Code

public partial class Grid : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(@”Data Source=SQLSERVER2008;Initial Catalog=Employee;Integrated Security=True”);
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
public int intFlag = 0;
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
        private void BindData()
{
comm.CommandText = “select FName,MName,LName,Addr,MobNo from Employee”;
comm.Connection = conn;
sda.SelectCommand = comm;
sda.Fill(ds);
gdvEmployee.DataSource = ds;
gdvEmployee.DataBind();
ds.Clear();
}
        protected void gdvEmployee_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals(“New”))
{
btnInsert.Text = “Insert”;
intFlag = 0;
panelInsert.Visible = true;
}
if (e.CommandName.Equals(“Edit”))
{
btnInsert.Text = “Update”;
intFlag = 1;
//panelInsert.Visible = true;
}
}
        protected void gdvEmployee_RowEditing(object sender, GridViewEditEventArgs e)
{
txtFname.Text = gdvEmployee.Rows[e.NewEditIndex].Cells[3].Text;
txtMName.Text = gdvEmployee.Rows[e.NewEditIndex].Cells[4].Text;
txtLName.Text = gdvEmployee.Rows[e.NewEditIndex].Cells[5].Text;
txtAddr.Text = gdvEmployee.Rows[e.NewEditIndex].Cells[6].Text;
txtMobNo.Text = gdvEmployee.Rows[e.NewEditIndex].Cells[7].Text;
            comm.CommandText = “select ID from Employee where FName=\'” + txtFname.Text + “\’AND MName=\'” + txtMName.Text + “\’ AND LName=\'” + txtLName.Text + “\'”;
sda.DeleteCommand = comm;
sda.Fill(ds);
Session[“ID”] = Convert.ToInt32(ds.Tables[0].Rows[0][5]);
            ds.Clear();}


protected void gdvEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
comm.CommandText = “delete from Employee where FName=\'” + e.Values[0] + “\’AND MName=\'” + e.Values[1] + “\’ AND LName=\'” + e.Values[2] + “\'”;
sda.DeleteCommand = comm;
sda.Fill(ds);
ds.Clear();
if (!Page.IsCallback)
BindData();
}
        protected void btnInsert_Click(object sender, EventArgs e)
{
if (intFlag == 1)
{
}
else
{
comm.CommandText = “insert into Employee (FName,MName,LName,Addr,MobNo)values(\'” + txtFname.Text + “\’,\'” + txtMName.Text + “\’,\'” + txtLName.Text + “\’,\'” + txtAddr.Text + “\’,\'” + txtMobNo.Text + “\’)”;
sda.InsertCommand = comm;
sda.Fill(ds);
panelInsert.Visible = false;
ds.Clear();
}
DataClear();
if (!Page.IsCallback)
BindData();
}

        private void DataClear()
{
txtFname.Text = “”;
txtMName.Text = “”;
txtLName.Text = “”;
txtAddr.Text = “”;
txtMobNo.Text = “”;
}
        protected void gdvEmployee_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
        }
        protected void gdvEmployee_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
comm.CommandText = “UPDATE Employee SET Fname=\'” + e.NewValues[0] + “\’, MName=\'” + e.NewValues[1] + “\’,LName=\'” + e.NewValues[2] + “\’,Addr=\'” + e.NewValues[3] + “\’,MobNo=\'” + e.NewValues[4] + “\’ WHERE ID=\'” + Convert.ToInt32(Session[“ID”]) + “\'”;
sda.UpdateCommand = comm;
sda.Fill(ds);
panelInsert.Visible = false;
ds.Clear();
if (!Page.IsCallback)
BindData();
}
      }

One thought on “Basic Gridview CRUD operations

  1. hide Row while editing Gridview ;
    gvShowData.HeaderRow.Cells[0].Visible = false;
    //foreach (GridViewRow gvr in Grd_show.Rows)
    //{
    //gvr.Cells[0].Visible = false;
    //}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s