Thursday, 17 January 2013

How To Update Gird View in Asp.Net

This article will give you an overview of how to use an asp:GridView completely, and how to use RowEditing,RowUpdating, RowDeleting, RowCommandRowCancelingEdit, and Pagination in a DataGrid. From this article, you will have a clear view of the GridView data  delete, and update operations.

Create Sql Table:
Create Table Employee
(
ID int,
Firstname nvarchar(50),
Lastname nvarchar(50),
DateOfBirth nvarchar(50),
JobTitle nvarchar(50),
Location nvarchar(50),
EmailAddress nvarchar(50)
)

Web.Config Connection string:

<connectionStrings>
  <add name="myconnectionstring" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=
|DataDirectory|\srujan.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
   providerName="System.Data.SqlClient" />
 </connectionStrings>

 
Design  page:  

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Employee1.aspx.cs" Inherits="employdetails.Employee1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/
TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="font-weight: 700; color: #000066">
  <asp:Table ID="formtable" runat="server" HorizontalAlign="Center" Caption=" EMPLOYEE FORM" >
 <asp:TableRow >
  <asp:TableCell>
     EmpID
  </asp:TableCell>
  <asp:TableCell>
   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  </asp:TableCell>
  </asp:TableRow>
  

<asp:TableRow >
  <asp:TableCell>
  FirstName
  </asp:TableCell>
  <asp:TableCell>
  <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
  </asp:TableCell>
  </asp:TableRow>
  

<asp:TableRow >
  <asp:TableCell>
  LastName
  </asp:TableCell>
  <asp:TableCell>
  <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
  </asp:TableCell>
  </asp:TableRow>
  

<asp:TableRow >
  <asp:TableCell>
  DateOfBirth
  </asp:TableCell>
  <asp:TableCell>
 <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
  </asp:TableCell>
  </asp:TableRow>
  

<asp:TableRow >
  <asp:TableCell>
   JobTitle
  </asp:TableCell>
  <asp:TableCell>
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
  </asp:TableCell>
  </asp:TableRow>
  

<asp:TableRow >
  <asp:TableCell>
    Location
  </asp:TableCell>
  <asp:TableCell>
 <asp:TextBox ID="TextBox6" runat="server" ></asp:TextBox>
  </asp:TableCell>
  </asp:TableRow>
  

<asp:TableRow >
  <asp:TableCell>
  EmailAddress
  </asp:TableCell>
  <asp:TableCell>
  <asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
  </asp:TableCell>
  </asp:TableRow>
     

 <asp:TableRow>
 <asp:TableCell>
</asp:TableCell>
      <asp:TableCell>
      <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
      </asp:TableCell>
      </asp:TableRow> 
    </asp:Table>
            <br />
            <br />
            <br />
        <br />
        <%-- GridView start from here --%>  
<asp:GridView ID="Gridview1" HorizontalAlign="Center" runat="server"
 AutoGenerateColumns="false" OnRowCancelingEdit="GridView1_RowCancelingEdit" 
DataKeyNames="ID,Firstname" OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating"OnRowDeleting="GridView1_RowDeleting">
 
 <%-- Header Of Grid View --%> 
<HeaderStyle BackColor="Blue" ForeColor="White" HorizontalAlign="Left"
 Height="20" />
 
 <%-- Grid View columns ID, Firstname, Lastname, DateofBirth, JobTitle, Location, 
EmailAddress --%>            
<Columns>
<asp:CommandField ShowEditButton="true" ShowDeleteButton="true"  
ShowCancelButton="true"ButtonType="Button" />

                    <%-- We con't Edit this BoundField --%>

<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="true" />
<asp:TemplateField HeaderText="Firstname">
<ItemTemplate><%# Eval ("Firstname") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="textFirstname" Text='<%#Eval("Firstname") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
                
<asp:TemplateField HeaderText="Lastname">
<ItemTemplate><%#Eval ("Lastname") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="textLastname" Text='<%#Eval("Lastname") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
               
               
<asp:TemplateField HeaderText="DateOfBirth">
<ItemTemplate><%#Eval("DateOfBirth")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="textDateOfBirth" Text='<%#Eval("DateOfBirth") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
               
               
<asp:TemplateField HeaderText="JobTitle">
<ItemTemplate><%#Eval("JobTitle")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="textJobTitle" Text='<%#Eval("JobTitle") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
               
               
               
<asp:TemplateField HeaderText="Location">
<ItemTemplate><%#Eval("Location")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="textLocation" Text='<%#Eval("Location") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
                
                
                
<asp:TemplateField HeaderText="EmailAddress">
<ItemTemplate><%#Eval("EmailAddress")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="textEmailAddress" Text='<%#Eval("EmailAddress") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
    </div>
    </form>
</body>
</html>
 
 

Code Behind:


 

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

namespace employdetails
{
    public partial class Employee1 : System.Web.UI.Page
    {
protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                bind();
            }
        }

        
 
protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["myconnectionstring"].ConnectionString);
con.Open();
SqlCommand cmm = new SqlCommand("insert into Employee values(" + Convert.ToInt32
(TextBox1.Text) + ", '" + TextBox2.Text + "', '" + TextBox3.Text + "', '"  
+ TextBox4.Text + "', '" + TextBox5.Text + "', '" + TextBox6.Text + "', '"  
+ TextBox7.Text + "')",con);
cmm.ExecuteNonQuery();
bind();
        }
 
// data bind method
        public void bind()
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["myconnectionstring"].ConnectionString);
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("select * from Employee", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            Gridview1.DataSource = dt;
            Gridview1.DataBind();
            con.Close();
        }
       
// selecting a row index for editing 
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            Gridview1.EditIndex = e.NewEditIndex;
            bind();
        }
 
// Row Editing Canceling Event
 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            e.Cancel = true;
            Gridview1.EditIndex = -1;
            bind();
        }
 
// Row Updating Event
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow row = Gridview1.Rows[e.RowIndex];
            TextBox textFirstname = (TextBox)row.FindControl("textFirstname");
            TextBox textLastname = (TextBox)row.FindControl("textLastname");
            TextBox textDateOfBirth = (TextBox)row.FindControl("textDateOfBirth");
            TextBox textLocation = (TextBox)row.FindControl("textLocation");
            TextBox textJobTitle = (TextBox)row.FindControl("textJobTitle");
            TextBox textEmailAddress = (TextBox)row.FindControl("textEmailAddress");
            int ID = Int32.Parse(Gridview1.DataKeys[e.RowIndex].Value.ToString());
            string Firstname = textFirstname.Text.ToString();
            string Lastname = textLastname.Text.ToString();
            string DateOfBirth = textDateOfBirth.Text.ToString();
            string JobTitle = textJobTitle.Text.ToString();
            string Location = textLocation.Text.ToString();
            string EmailAddress = textEmailAddress.Text.ToString();
            updatedetails(ID, Firstname, Lastname, DateOfBirth, JobTitle, 
Location, EmailAddress); 
// calling a update method
        }
//updatedetails method definition  
        public void updatedetails(int ID, string Firstname, string Lastname,  
string DateOfBirth, string JobTitle, string Location, string EmailAddress)
        {
string query = "UPDATE Employee SET Firstname = @Firstname, Lastname=@Lastname, 
DateOfBirth=@DateOfBirth, JobTitle=@JobTitle, Location=@Location, 
EmailAddress=@EmailAddress WHERE ID = @ID";
                SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["myconnectionstring"].ConnectionString);
                con.Open();
                SqlCommand com = new SqlCommand(query, con);
                com.Parameters.Add("@ID", SqlDbType.Int).Value = ID;
                com.Parameters.Add("@Firstname", SqlDbType.VarChar).Value = Firstname;
                com.Parameters.Add("@Lastname", SqlDbType.VarChar).Value = Lastname;
                com.Parameters.Add("@DateOfBirth", SqlDbType.VarChar).Value = DateOfBirth;
                com.Parameters.Add("@JobTitle", SqlDbType.VarChar).Value = JobTitle;
                com.Parameters.Add("@Location", SqlDbType.VarChar).Value = Location;
                com.Parameters.Add("@EmailAddress",SqlDbType.VarChar).Value = EmailAddress;
                com.ExecuteNonQuery();
                Gridview1.EditIndex = -1;
                bind();
            
            
        }
        
// row deleting Event:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["myconnectionstring"].ConnectionString);
            con.Open();
            int ID = Int32.Parse(Gridview1.DataKeys[e.RowIndex].Value.ToString()); 
            string Firstname = Gridview1.DataKeys[e.RowIndex].Values["Firstname"].ToString();
           
            SqlCommand cmd = new SqlCommand("delete from Employee where ID=" + ID+ " and 
Firstname=Firstname", con);
            int result = cmd.ExecuteNonQuery();
            bind();
            con.Close();
        }
    }
}






 

No comments:

Post a Comment