Wednesday, August 6, 2008

Grid - Code Approach

This code handle the grid. Manual with code approach Edit,delete records from grid.

Create table with following columns

Eno bigint - autoincrement
name varchar(100)
salary bigint


ASPX.cs Code - default.aspx.cs


using System;
using System.Data;
using System.Data.SqlClient;
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;

public partial class _Default : System.Web.UI.Page
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings.Get("cn").ToString());

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (cn.State != ConnectionState.Open)
{
cn.Open();
}

bindgrid();
}
}
private void bindgrid()
{
SqlDataAdapter ad = new SqlDataAdapter("select * from emp", cn);
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}


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

Label lbleno = (Label)GridView1.Rows[e.RowIndex].FindControl("lbl_eno");
TextBox txtname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_name");
TextBox txtsalary = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_salary");

if (cn.State != ConnectionState.Open)
{
cn.Open();
}

SqlCommand cmd = new SqlCommand("update emp set name='" + txtname.Text + "',salary=" + txtsalary.Text + " where eno=" + lbleno.Text, cn);
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
bindgrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

Label lbleno = (Label)GridView1.Rows[e.RowIndex].FindControl("lbl_no");

if (cn.State != ConnectionState.Open)
{
cn.Open();
}

SqlCommand cmd = new SqlCommand("delete from emp where eno=" + lbleno.Text, cn);
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
bindgrid();
}
}

No comments: