Grid View Commands Select, Edit, Update, Cancel Example


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.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(@"Initial Catalog=DB;Data Source=JAIMATARANI;User ID=sa;Password=123;Min Pool Size=5;Max Pool Size=60;Connect Timeout=2");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    //Bind Grid View
    protected void BindGrid()
    {
        SqlDataAdapter da = new SqlDataAdapter("Select * from Student", con);
        DataSet ds = new DataSet();
        da.Fill(ds, "T1");
        GridView1.DataSource = ds.Tables["T1"];
        GridView1.DataBind();
    }
  //Edit
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
     
        BindGrid();
    }
    //Cancel
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindGrid();
    }
    //Update
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        SqlCommand cmd = new SqlCommand(@"Update Student Set
EnrollmentNo='" + (((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text) + @"',
Name='" + (((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text) + @"',
Programme='" + (((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text) + @"',
Address='" + (((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text) + @"',
Mobile='" + (((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text) + @"'
where SL_No='" + (((TextBox)GridView1.Rows[e.RowIndex].Cells [0].Controls[0]).Text) + @"'", con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        GridView1.EditIndex = -1;
        BindGrid();
    }
    //Delete
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        SqlCommand cmd = new SqlCommand("Delete from Student where SL_No='"+GridView1 .Rows [e.RowIndex ].Cells [0].Text +"'", con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        BindGrid();
    }
    //Select
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        SqlDataAdapter da = new SqlDataAdapter("Select * from Student where SL_No='" + GridView1 .SelectedRow .Cells [0].Text  + "' ", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        DetailsView1.DataSource = ds;
        DetailsView1.DataBind();
    }
}

0 comments:

Post a Comment