Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Wednesday, 5 August 2015

In this article I will explain how to add, update and delete data in gridview. I will use Row_Command Event to do all these tasks. Follow the given steps:


Implementation:
1.     Create a database i.e. “Blog”.Then create a table “Student_Info”.
Column Name
Datatype
Student_id
Int(Primary Key. So set Is Identity=True)
Student_Name
Varchar(500)
Age
int
Class
Varchar(50)

2.     Stored Procedure:
  create proc [dbo].[Fill_Dataset]
     as
     select * from student_info
3.     Create Connection: Now create connection in  webcofig file as given below.
<connectionStrings>
<addname="con"connectionString="Data Source=localhost; Initial Catalog=Blog; Integrated Security=true;"providerName="System.Data.SqlClient"/>

</connectionStrings>
 4.  GridView design: Design your gridview as given below.

         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCommand="GridView1_RowCommand" ShowFooter="True" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
                <asp:TemplateField HeaderText="Name">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Student_name") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("Student_name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Age">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Age") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("Age") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="class">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("class") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtClass" runat="server"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("class") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
         <asp:TemplateField>
            <ItemTemplate>
             <asp:Button ID="btnedit" runat="server" Text="Edit" CommandName="Edit" CommandArgument='<%#Bind("Student_id") %>'  CausesValidation="false"/>
                <asp:Button ID="btndelete" runat="server" Text="Delete" OnClientClick="return confirm('Do you want to delete this record?')" CommandName="Delete" CommandArgument='<%#Bind("Student_id") %>' CausesValidation="false" CssClass="btn"/>
            </ItemTemplate>
                <EditItemTemplate>
                    <asp:Button ID="btnupdate" runat="server" Text="Update"  CommandName="Update" CommandArgument='<%#Bind("Student_id") %>'  CausesValidation="false"/><asp:Button ID="btncancel" runat="server" Text="Cancel" CommandArgument='<%#Bind("Student_id") %>'   CommandName="Cancel" CausesValidation="false" CssClass="btn" />
                </EditItemTemplate>
            <FooterTemplate>
                <asp:Button ID="btninsert" runat="server" Text="Insert Record" CommandArgument='<%#Bind("Student_id") %>' CommandName="Insert" />
            </FooterTemplate>
              
        </asp:TemplateField>
            </Columns>
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
        </asp:GridView>


Asp.Net Code Using C#:

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 editGrid : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Fill_Grid();
        }
    }
    //Fetch data from database and bind to gridview
    public void Fill_Grid()
    {
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
        con.Open();
        DataSet ds = new DataSet();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "Fill_Dataset";
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter dataadapater = new SqlDataAdapter();
        dataadapater.SelectCommand = cmd;
        dataadapater.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        cmd.Dispose();
        con.Close();
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
 
   if (e.CommandName == "Insert")
        {
            SqlCommand cmd = new SqlCommand("Insert into Student_info(Student_Name,Age,Class) values(@name,@age,@class)", con);
            TextBox txtname = (TextBox)GridView1.FooterRow.FindControl("txtname");
            TextBox txtAge = (TextBox)GridView1.FooterRow.FindControl("txtAge");
            TextBox txtclass = (TextBox)GridView1.FooterRow.FindControl("txtclass");
            con.Open();
            cmd.Parameters.AddWithValue("@name", txtname.Text);
            cmd.Parameters.AddWithValue("@age", txtAge.Text);
            cmd.Parameters.AddWithValue("@class", txtclass.Text);
            cmd.ExecuteNonQuery();
            con.Close();
            Response.Write("<script type=\"text/javascript\">alert('Record Insert Successfully!!!');</script>");
            Fill_Grid();
            txtname.Text = string.Empty;
            txtAge.Text = string.Empty;
            txtclass.Text = string.Empty;
        }
 
   if (e.CommandName == "Delete")
   {
       int id = Convert.ToInt32(e.CommandArgument.ToString());
       if (con.State == ConnectionState.Open)
       {
           con.Close();
       }
       con.Open();
       SqlCommand cmd = new SqlCommand();
       cmd.Connection = con;
       cmd.CommandText = "Delete from student_Info where student_id=" + id + "";
       cmd.ExecuteNonQuery();
       cmd.Dispose();
       con.Close();

       Fill_Grid();
   } 
   if (e.CommandName == "Update")
   {
       int id = Convert.ToInt32(e.CommandArgument.ToString());
       Button btn = (Button)e.CommandSource;
       GridViewRow gvrow = ((GridViewRow)btn.NamingContainer);   
        TextBox txtName = (TextBox)GridView1.Rows[gvrow.RowIndex].FindControl("TextBox1");
        TextBox txtAge = (TextBox)GridView1.Rows[gvrow.RowIndex].FindControl("TextBox2");
        TextBox txtClass = (TextBox)GridView1.Rows[gvrow.RowIndex].FindControl("TextBox3");

       if (con.State == ConnectionState.Open)
       {
           con.Close();
       }
       con.Open();
       SqlCommand cmd = new SqlCommand();
       cmd.Connection = con;
       cmd.CommandText = "update student_info set Student_name=@name, age=@age, class=@class where student_id=@id";
       cmd.Parameters.AddWithValue("@name", txtName.Text);
       cmd.Parameters.AddWithValue("@age", txtAge.Text);
       cmd.Parameters.AddWithValue("@class", txtClass.Text);
       cmd.Parameters.AddWithValue("@id", id);
       cmd.ExecuteNonQuery();
       cmd.Dispose();

       con.Close();
       GridView1.EditIndex = -1;
       Fill_Grid();
       Response.Write("<script> alert('Record updated successfully')</script>");
   }
}
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        Fill_Grid();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        Fill_Grid();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

    }
}
Categories: , ,

0 comments:

Post a Comment