Thursday, 9 February 2012

USE OF GRID VIEW IN ASP.NET (GRID VIEW EVENTS



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;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
        GridDataBind();
     }

    public void GridDataBind()
     {


    String constr = ConfigurationSettings.AppSettings["constr"];
    SqlConnection con = new SqlConnection(constr);
    SqlCommand com = new SqlCommand("select * from Table_Name", con);

    con.Open();
    SqlDataReader dr = com.ExecuteReader();
    GridView1.DataSource = dr;
    GridView1.DataBind();
    con.Close();
      }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
     {
    GridViewRow row = GridView1.Rows[e.RowIndex];
    DataKey key;
     if (row != null)
      {
     key = GridView1.DataKeys[row.RowIndex];
     TextBox txtname = (TextBox)row.FindControl("txtname");
     TextBox txtpass = (TextBox)row.FindControl("txtpass");
     string strname = txtname.Text;
     string strpass = txtpass.Text;
     string constr = ConfigurationSettings.AppSettings["constr"];
     SqlConnection conn = new SqlConnection(constr);
     SqlCommand com = new SqlCommand("update Table_Name set               
     name='"+strname+"', pass='"+strpass+"' where ID='"+key.Value+"'", conn);
     conn.Open();
     com.ExecuteNonQuery();
     conn.Close();
     GridView1.EditIndex = -1;
     GridDataBind();
      }
      }
     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
     {
     GridView1.EditIndex = e.NewEditIndex;
     GridDataBind();
      }
   protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgse)
     {
     GridView1.EditIndex = -1;
     GridDataBind();
      }
      protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
      {
      GridViewRow row = GridView1.Rows[e.RowIndex];
      DataKey key ;
      key = GridView1.DataKeys[row.RowIndex];
      if (row != null)
      {
      String constr = ConfigurationSettings.AppSettings["constr"];
      SqlConnection conn = new SqlConnection(constr);
      SqlCommand com = new SqlCommand();
      conn.Open();
      com.CommandText = "delete from Table_Name where ID='" + key.Value + "'";
      com.Connection = conn;
      com.ExecuteNonQuery();
      conn.Close();
      }
      GridDataBind();
      }
      }
Table_Name, Append Setting, Execute Query, Newedit Index, Web.Security, Grid View


No comments:

Post a Comment