Monday 10 December 2012

Insert , Update and Delete through GridView in Asp.Net.


In this post I will explain how to insert , Update and Delete Data through GridView in Asp.Net.

In the previous post I had explained Insert , Update and Delete without writing any code in GridView in Asp.Net .

Decription:-

In this article I have taken a gridview in which there are textbox and label to show the data and edit the data. I have also taken a textbox in footer to insert the data in the existing data in gridview in asp.net . For this we have call rowCommand property to insert the data. It’s better to follow the step which is decribed below..
First Create a table in DataBase like this..

Create table User_Details(id int primary key set identity true, name varchar(50),city varchar(50), country varchar(50));

Then after create a design page and paste the given code .

Design page :-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
            GridLines="None" AutoGenerateColumns="False" DataKeyNames="id,name"
            onrowcancelingedit="GridView1_RowCancelingEdit" PageSize="2"
            onrowcommand="GridView1_RowCommand" onrowdeleting="GridView1_RowDeleting"
            onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
            ShowFooter="True">
            <AlternatingRowStyle BackColor="White" />
            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
            <SortedAscendingCellStyle BackColor="#FDF5AC" />
            <SortedAscendingHeaderStyle BackColor="#4D0000" />
            <SortedDescendingCellStyle BackColor="#FCF6C0" />
            <SortedDescendingHeaderStyle BackColor="#820000" />
            <Columns>
            <asp:TemplateField>
            <EditItemTemplate>
                <asp:Button ID="btnUpdate" runat="server" CommandName="Update" Text="Update" />
                <asp:Button ID="btnCancel" runat="server" CommandName="Cancel" Text="Cancel" />
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Button ID="btnEdit" runat="server" CommandName="Edit" Text="Edit" />
                <asp:Button ID="btnDelete"  runat="server" CommandName="Delete" Text="Delete" />
            </ItemTemplate>
            <FooterTemplate>
            <asp:Button ID="btnAddNew" runat="server" CommandName="AddNew" Text="Add" ToolTip="Add New " ValidationGroup="validation"/>
            </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name">
            <EditItemTemplate>
            <asp:TextBox ID="txtName" runat="server" Text='<%#Eval("name") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
            <asp:Label ID="lblName" runat="server" Text='<%#Eval("name") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtFtrName" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Text="*" ValidationGroup="validation" ControlToValidate="txtFtrName"></asp:RequiredFieldValidator>
            </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City">
            <EditItemTemplate>
            <asp:TextBox ID="txtCity" runat="server" Text='<%#Eval("city") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
            <asp:Label ID="lblCity" runat="server" Text='<%#Eval("city") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtFtrCity" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Text="*" ValidationGroup="validation" ControlToValidate="txtFtrCity"></asp:RequiredFieldValidator>
            </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Country">
            <EditItemTemplate>
            <asp:TextBox ID="txtCountry" runat="server" Text='<%#Eval("country") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
            <asp:Label ID="lblCountry" runat="server" Text='<%#Eval("country") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtFtrCountry" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" Text="*" ValidationGroup="validation" ControlToValidate="txtFtrCountry"></asp:RequiredFieldValidator>
            </FooterTemplate>
            </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:Label ID="lblMessage" runat="server" ></asp:Label>
    </div>
    </form>
</body>
</html>

Code Behind page:-
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;

public partial class gridView_InsertUpdateDeleteInGridView : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(@"Data Source=SUSHIL-PC;Initial Catalog=modi;Integrated Security=True");
    SqlCommand com;
    SqlDataAdapter da;
    DataSet ds;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridView();
        }
    }
    void BindGridView()
    {
        con.Open();
        com = new SqlCommand("select * from User_Details",con);
        da = new SqlDataAdapter(com);
        ds = new DataSet();
        da.Fill(ds);
        con.Close();
        if (ds.Tables[0].Rows.Count > 0)
        {
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        else
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            GridView1.DataSource = ds;
            GridView1.DataBind();
            int columnCount = GridView1.Rows[0].Cells.Count;
            GridView1.Rows[0].Cells.Clear();
            GridView1.Rows[0].Cells.Add(new TableCell());
            GridView1.Rows[0].Cells[0].ColumnSpan = columnCount;
            GridView1.Rows[0].Cells[0].Text = "No Record Found....";
        }
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if(e.CommandName.Equals("AddNew"))
        {
            TextBox txtName = (TextBox)GridView1.FooterRow.FindControl("txtFtrName");
            TextBox txtCity = (TextBox)GridView1.FooterRow.FindControl("txtFtrCity");
            TextBox txtCountry = (TextBox)GridView1.FooterRow.FindControl("txtFtrCountry");
            con.Open();
            com = new SqlCommand("insert into User_Details values('"+txtName.Text+"','"+txtCity.Text+"','"+txtCountry.Text+"')",con);
            int result = com.ExecuteNonQuery();
            con.Close();
            if (result == 1)
            {
                BindGridView();
                lblMessage.ForeColor = System.Drawing.Color.Green;
                lblMessage.Text = "Data Inserted Successfully.";
            }
            else
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "Details not Inserted .";
            }
        }
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int userId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
        TextBox txtname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
        TextBox txtcity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCity");
        TextBox txtcountry = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCountry");
        con.Open();
        com = new SqlCommand("update User_Details set name='" + txtname.Text + "',city='" + txtcity.Text + "',country='" + txtcountry.Text + "' where id=" + userId, con);
        com.ExecuteNonQuery();
        con.Close();
        lblMessage.ForeColor = System.Drawing.Color.Blue;
        lblMessage.Text = "Update Successfully.";
        GridView1.EditIndex = -1;
        BindGridView();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
        con.Open();
        com = new SqlCommand("Delete From User_Details where id="+id,con);
        int result = com.ExecuteNonQuery();
        con.Close();
        if (result == 1)
        {
            BindGridView();
            lblMessage.ForeColor = System.Drawing.Color.Green;
            lblMessage.Text = "Datails Deleted Successfully.";
        }
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindGridView();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindGridView();
    }
}

Debug and Run .

No comments:

Post a Comment

Note: only a member of this blog may post a comment.