Wednesday 2 January 2013

ASP.NET GRIDVIEW- INSERT, UPDATE, DELETE

ALL THE BEST!!!

It's Very Simple Just Do Paste This Code And Get Your Desire;


1. Create Table As


CREATE TABLE [dbo].[test_table](
      [MID] [int] NOT NULL,
      [MName] [char](30) NULL,
      [MSal] [nchar](30) NULL,
      [MAdd] [char](50) NULL
)

2. Paste AXPX Page in AXPX File and C# in Business Logic Page:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="aaaa.aspx.cs" Inherits="aaaa" %>

<!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>  
          
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="MID"
                    ShowFooter="True" Style="z-index: 1; left: 121px; top: 77px; position: absolute;
                    height: 133px; width: 754px" OnRowCancelingEdit="GridView1_RowCancelingEdit"
                    OnRowEditing="GridView1_RowEditing" BackColor="LightGoldenrodYellow" BorderColor="Tan"
                    BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None" OnRowCommand="GridView1_RowCommand"
                    OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating">
                    <FooterStyle BackColor="Tan" />
                    <Columns>
                        <asp:TemplateField HeaderText="Edit-Delete">
                            <EditItemTemplate>
                                <asp:LinkButton ID="lnkUpdate" Text="Update" CommandName="Update" runat="server"></asp:LinkButton>
                                <asp:LinkButton ID="lnkcancel" Text="Cancel" CommandName="Cancel" runat="server"></asp:LinkButton>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:LinkButton ID="lnkEdit" Text="Edit" CommandName="Edit" runat="server"></asp:LinkButton>
                                <asp:LinkButton ID="LnkDelete" Text="Delete" CommandName="Delete" runat="server"></asp:LinkButton>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:LinkButton ID="lnkAddNew" Text="AddNew" CommandName="Insert" runat="server"></asp:LinkButton>
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="ID">
                            <EditItemTemplate>
                                <asp:Label ID="lblid" runat="server" Text='<%#Eval("MID")%>' />
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="lblid" runat="server" Text='<%#Eval("MID")%>' />
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="txtfid" runat="server" />
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Name">
                            <EditItemTemplate>
                                <asp:TextBox ID="txtname" runat="server" Text='<%#Bind("MName")%>' />
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="lblname" runat="server" Text='<%#Eval("MName")%>' />
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="txtfname" runat="server" />
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Salary">
                            <EditItemTemplate>
                                <asp:TextBox ID="txtsal" runat="server" Text='<%#Bind("MSal")%>' />
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="lblsal" runat="server" Text='<%#Eval("MSal")%>' />
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="txtfsal" runat="server" />
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Address">
                            <EditItemTemplate>
                                <asp:TextBox ID="txtadd" runat="server" Text='<%#Bind("MAdd")%>' />
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="lbladd" runat="server" Text='<%#Eval("MAdd")%>' />
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="txtfadd" runat="server" />
                            </FooterTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
                    <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
                    <HeaderStyle BackColor="Tan" Font-Bold="True" />
                    <AlternatingRowStyle BackColor="PaleGoldenrod" />
                </asp:GridView>
            </div>
    </div>
    </form>
</body>
</html>

**********************************************************************************
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.IO;
    using System.Data ;
    using System.Data .SqlClient ;
    using System.Text ;

    public partial class aaaa : System.Web.UI.Page
    {
        private SqlConnection conn = new SqlConnection("Data Source=Server-Name; database=test_base; User Id=sa; Password=saa;");
        DataSet ds = new DataSet();
        protected void Page_Load(object sender, EventArgs e)
        {
        if (!IsPostBack)
        {
        fillgrid();
        }
    }
    protected void fillgrid()
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand("select * from test_table",conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        conn.Close();
        if (ds.Tables[0].Rows.Count > 0) // dt.rows.count
        {
        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; // It counts no. of coln in databse'stable.
        GridView1.Rows[0].Cells.Clear();
        GridView1.Rows[0].Cells.Add(new TableCell());
        GridView1.Rows[0].Cells[0].ColumnSpan = columncount; // here it spaning column.....
        GridView1.Rows[0].Cells[0].Text = "No Records Found";
        // If textbox in taken in itemtemplate or in else ... then if table is blank in database
        // then it shows blank textbox and NO record found. else only no record found...
        }

    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        fillgrid();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        fillgrid();
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if(e.CommandName.Equals("Insert"))// Must write this line else code confused whichcommand to execute
        {
            TextBox txtfid = (TextBox)GridView1.FooterRow.FindControl("txtfid");
            TextBox txtfname = (TextBox)GridView1.FooterRow.FindControl("txtfname");
            TextBox txtfsal = (TextBox)GridView1.FooterRow.FindControl("txtfsal");
            TextBox txtfadd = (TextBox)GridView1.FooterRow.FindControl("txtfadd");
            conn.Open();
            SqlCommand cmd =new SqlCommand("insert into test_table(MID,MName,MSal,MAdd)values('" + txtfid.Text + "','" +txtfname.Text + "','" + txtfsal.Text + "','" + txtfadd.Text + "')",conn);

            int result = cmd.ExecuteNonQuery();
            conn.Close();
        if (result == 1)
        {
            fillgrid();
            Response.Write("Saved");
        }
        else
        {
            Response.Write("Not Saved");
        }

        }
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int key = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["MID"].ToString());
        conn.Open();
        SqlCommand cmd = new SqlCommand("delete from test_table where MID=" + key, conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        fillgrid();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int index = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["MID"].ToString());
        Label txtid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblid");
        TextBox txtname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtname");
        TextBox txtsal = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtsal");
        TextBox txtadd = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtadd");
        conn.Open();
        SqlCommand cmd = new SqlCommand("update test_table set MName='" + txtname.Text +
        "',MSal='" + txtsal.Text + "',MAdd='" + txtsal.Text + "' where MID=" + index, conn);
        int count = cmd.ExecuteNonQuery();
        conn.Close();
        GridView1.EditIndex = -1;
        fillgrid();
        if (count == 1)
        {
        Response.Write("Updated " + index);
        }
        else
        {
        Response.Write("Not Updated");
        }

        }

    }


 

No comments:

Post a Comment