Wednesday, 2 May 2012

Edit and Update record in Grid View in asp.net


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            data_bind();
        }

    }

    private void data_bind()
    {
        SqlDataAdapter adp = new SqlDataAdapter("select * from tbemp1", ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        data_bind();

    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Int32 empno,esl;
        String enam, eadd;

        enam = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("t1"))).Text;
        eadd = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("t2"))).Text;
        esl = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].FindControl("t3"))).Text);
        empno = Convert.ToInt32(((Label)(GridView1.Rows[e.RowIndex].FindControl("lk"))).Text);

        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "Update tbemp1 set ename = @enam,eadd = @ed,esal = @esl where empno = @eno";
        cmd.Connection = con;
        cmd.Parameters.Add("@eno", SqlDbType.Int).Value = empno;
        cmd.Parameters.Add("@enam", SqlDbType.VarChar, 50).Value = enam;
        cmd.Parameters.Add("@ed", SqlDbType.VarChar, 50).Value = eadd;
        cmd.Parameters.Add("@esl", SqlDbType.Int).Value = esl;
        cmd.ExecuteNonQuery();
        cmd.Dispose();
        GridView1.EditIndex = -1;
        data_bind();


    }
   
}



No comments:

Post a Comment

QUICK REVISION of the Informatics Practices Examination

QUICK REVISION of the Informatics Practices Examination Data Types Every value belongs to a specific data type in Python. Data type iden...