Saturday, 5 May 2012

ASP.NET Insert ,Edit ,Update

Introduction:

In this article I will explain how to insert, edit, update and delete data in gridview using asp.net.


Description: 

I have one gridview I need to write code to insert data into gridview after that I need to edit that gridview data and update it and if I want to delete the record in grdview we need to delete record simply by click on delete button of particular row to achieve these functionalities I have used some of gridview events those are 

1)      1) Onrowcancelingedit
2)      2) Onrowediting
3)      3) Onrowupdating
4)      4) Onrowcancelingedit
5)      5) Onrowdeleting

By Using above griview events we can insert, edit, update and delete the data in gridview. My Question is how we can use these events in our coding before to see those details first design  table in database and give name Employee_Details


ColumnName
DataType
UserId
Int(set identity property=true)
UserName
varchar(50)
City
varchar(50)
Designation
varchar(50)
After completion table creation design aspx page like this
 

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
                        Width="440px" onrowcancelingedit="GridView1_RowCancelingEdit"
                        onrowupdating="GridView1_RowUpdating" onrowediting="GridView1_RowEditing"
                        ShowFooter="true" onrowcommand="GridView1_RowCommand">
                    <Columns>
                  
                    <asp:TemplateField HeaderText="Name">
                    <EditItemTemplate>
                    <asp:TextBox ID="txtname" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                    <asp:Label ID="lblname" runat="server" Text='<%# Bind("name") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterStyle HorizontalAlign="Right" />
                    <FooterTemplate>
                    <asp:TextBox ID="txtname" runat="server" ></asp:TextBox>
                    </FooterTemplate>
                 
                  
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="EmailId">
                    <EditItemTemplate>
                      <asp:TextBox ID="txtmail" runat="server" Text='<%# Bind("email") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                    <asp:Label ID="lblmail" runat="server" Text='<%# Bind("email") %>'></asp:Label></ItemTemplate>
                     <FooterStyle HorizontalAlign="Right" />
                    <FooterTemplate>
                    <asp:TextBox ID="txtmail" runat="server"  ></asp:TextBox>
                    </FooterTemplate>
                 
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="MobileNo">
                    <EditItemTemplate>
                    <asp:TextBox ID="txtmno" Text='<%# Bind("Mobileno") %>' runat="server"></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                    <asp:Label ID="lblmno" runat="server" Text='<%# Bind("MobileNo") %>'></asp:Label>
                    </ItemTemplate>
                     <FooterStyle HorizontalAlign="Right" />
                    <FooterTemplate>
                    <asp:TextBox ID="txtmno" runat="server" ></asp:TextBox>
                    </FooterTemplate>
                 
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Comment">
                    <EditItemTemplate>
                    <asp:TextBox ID="txtcomment" runat="server" Text='<%# Bind("Comment") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate> <asp:Label ID="lblcomment" runat="server" Text='<%# Bind("Comment") %>'></asp:Label> </ItemTemplate>
                     <FooterStyle HorizontalAlign="Right" />
                  
                
                    <FooterTemplate>
                    <asp:TextBox ID="txtcomment" runat="server" ></asp:TextBox>
                  
                    </FooterTemplate>
                 
                  
                  

                  
                  
                    </asp:TemplateField>
                    <asp:TemplateField>
                    <FooterTemplate>
                     <asp:Button ID="Button1" runat="server"  CommandName="AddNew" Text="Add" />
                    </FooterTemplate>
                    </asp:TemplateField>
                    <asp:CommandField HeaderText="Edit" ShowEditButton="true" />
                
                    </Columns>
                  
                    </asp:GridView>
                    <asp:Label ID="lblresult" runat="server" Text="Label"></asp:Label></body></div></form>
  
After that add these namcespace using System.Data,using System.Drawing and usingSystem.Data.SqlClient in your codebehind and write the following code

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
public partial class Admin_view : System.Web.UI.Page
{
    SqlCommand cmd;
    SqlConnection con;
    DataSet ds;
    SqlDataAdapter da;
    protected void Page_Load(object sender, EventArgs e)
    {
        con = new SqlConnection(ConfigurationManager.AppSettings["hi"]);
        con.Open();
        if (!IsPostBack)
        {
            Label1.Text = "Welcome " + Session["s"].ToString();
            Response.Write("<script>alert('Welcome to Admin View Page')</script>");
            GridView1.Visible = false;
        }
    }
    protected void LinkButton4_Click(object sender, EventArgs e)
    {
        GridView1.Visible = true;
        gv();
    }
  
    public void gv()
    {
        con.Close();
        con.Open();
        cmd = new SqlCommand("select * from feed_back", con);
        da = new SqlDataAdapter(cmd);
        ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
          
            con.Close();
            con.Open();
         
            GridViewRow gvr = (GridViewRow)GridView1.Rows[e.RowIndex];
            TextBox tname = (TextBox)gvr.FindControl("txtname");
            TextBox tmail = (TextBox)gvr.FindControl("txtmail");
            TextBox tmno = (TextBox)gvr.FindControl("txtmno");
            TextBox tcomment = (TextBox)gvr.FindControl("txtcomment");
            string s = "update feed_back set email=@email,Mobileno=@mno,Comment=@comment where name=@name";
            cmd = new SqlCommand(s, con);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@email", tmail.Text);
            cmd.Parameters.AddWithValue("@mno", tmno.Text);
            cmd.Parameters.AddWithValue("@comment ", tcomment.Text);
            cmd.Parameters.AddWithValue("@name", tname.Text);
            //cmd = new SqlCommand("update feed_back set email='" + tmail.Text.ToString() .Trim()+ "',MobileNo='" + tmno.Text.ToString().Trim() + "',Comment='" + tcomment.Text .ToString().Trim()+ "' where name='" + tname.Text .ToString().Trim()+ "'", con);
            cmd.ExecuteNonQuery();
            con.Close();
            gv();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

    }
  
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        gv();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        gv();
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("AddNew"))
        {
            TextBox tname = (TextBox)GridView1.FooterRow.FindControl("txtname");
            TextBox temail = (TextBox)GridView1.FooterRow.FindControl("txtmail");
            TextBox tmno = (TextBox)GridView1.FooterRow.FindControl("txtmno");
            TextBox tcmt = (TextBox)GridView1.FooterRow.FindControl("txtcomment");
            con.Close();
            con.Open();
            SqlCommand cmd =
            new SqlCommand(
            "insert into feed_back(name,email,Mobileno,Comment) values('" + tname.Text + "','" +
            temail.Text + "','" + tmno.Text + "','" + tcmt.Text + "')", con);
            int result = cmd.ExecuteNonQuery();
            con.Close();
            if (result == 1)
            {
                gv();
                lblresult.ForeColor = Color.Green;
                lblresult.Text = " Details inserted successfully";
            }
            else
            {
                lblresult.ForeColor = Color.Red;
                lblresult.Text = " Details not inserted";
            }
        }
    }
}

No comments:

Post a Comment