Thursday, 4 April 2013

Code To Insert, Update, Delete Record In Sql Server DataBase Using Asp.net


Code To Insert, Update, Delete Record In Sql Server DataBase Using Asp.net (or) Perform Insert, Update,Delete Using Asp.net In C#
Now for this new article first create a new asp.net web application, and add a new page in it and add a gridview control. Here is your .aspx code.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="BindGridView.WebForm1" %>

<!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>How To Import Excelsheet Data Into SQL Server Using Asp.Net In c#</title>
    <script language="javascript">
        function ConfirmMessage() {
            var answer = confirm("Are you sure. do you want to delete record.");
            if (answer) {
                return true;
            } else {
                return false;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     
 
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Name :<asp:TextBox ID="TextBox1" runat="server"
 
            Width="200px"></asp:TextBox>
        <br />
        <br />
&nbsp;&nbsp;&nbsp; Address:<asp:TextBox ID="TextBox2" runat="server" Width="200px"></asp:TextBox>
        <br />
        <br />
        ContactNo :<asp:TextBox ID="TextBox3" runat="server" Width="200px"></asp:TextBox>
        <br />
        <br />
     
 
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save"
            Width="93px" />
                  <asp:Button ID="Button2" runat="server"  Text="Update"
            Width="93px" onclick="Button2_Click" />
        <br />
        <br />
        <asp:Label ID="lblmessage" runat="server"
 
            style="font-weight: 700; color: #FFFFFF; background-color: #FF0000"
 
            Text=""></asp:Label>
        <br />
        <br />
        <asp:GridView runat="server" AutoGenerateColumns="False" ID="griddemo"
 
            Width="540px" onrowcommand="griddemo_RowCommand">
            <Columns>
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:BoundField DataField="Address" HeaderText="Address" />
                <asp:BoundField DataField="ContactNo" HeaderText="Contact No" />
                <asp:TemplateField HeaderText="Edit">
                    <ItemTemplate>
                        <a href="WebForm1.aspx?ID=<%#Eval("Id") %>">Update</a>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Delete">
                    <ItemTemplate>
                        <asp:LinkButton ID="Delete" CommandName="Delete" runat="server" OnClientClick="javascript:return ConfirmMessage();">Delete</asp:LinkButton>
                        <asp:Label runat="server" Text=`<%#Eval("Id") %>` ID="lblid"></asp:Label>
                    </ItemTemplate>
                   
 
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>   
 
    </form>
</body>
</html>


Now add the below code in your .cs 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.SqlClient;
using System.Data;
using System.IO;
using System.Data.OleDb;

namespace BindGridView
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        SqlConnection objcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["ID"] == null)
            {
                Button1.Visible = true;
                Button2.Visible = false;
            }
            else
            {
                Button2.Visible = true;
                Button1.Visible = false;
                if (!IsPostBack)
                {
                    GetDataById(Request.QueryString["ID"].ToString());
                }
            }
            if (!IsPostBack)
            {
                BindGrid();
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                string query = "Insert into student([Name],[Address],[ContactNo]) values(`" + TextBox1.Text + "`,`" + TextBox2.Text + "`,`" + TextBox3.Text + "`);SELECT @@IDENTITY as Pkvalue;";
                SqlDataAdapter objda = new SqlDataAdapter(query, objcon);
                objcon.Open();
                objda.SelectCommand.ExecuteNonQuery();
                objcon.Close();
                lblmessage.Text = "Data saved successfully.";
                BindGrid();
            }
            catch
            {
                lblmessage.Text = "Error while saving the record.";
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable objdt = new DataTable();
                string query = "update student set [Name]=`" + TextBox1.Text + "`,[Address]=`" + TextBox2.Text + "`,[ContactNo]=`" + TextBox3.Text + "` where Id=" + Request.QueryString["ID"].ToString() + ";";
                SqlDataAdapter objda = new SqlDataAdapter(query, objcon);
                objcon.Open();
                objda.SelectCommand.ExecuteNonQuery();
                objcon.Close();
                lblmessage.Text = "Data updated successfully.";
                BindGrid();
            }
            catch
            {
                lblmessage.Text = "Error while saving the record.";
            }
        }
        private void GetDataById(string id)
        {
            try
            {
                DataTable objdt = new DataTable();
                string query = "select * from student where Id=`" + id + "`;";
                SqlDataAdapter objda = new SqlDataAdapter(query, objcon);
                objcon.Open();
                objda.Fill(objdt);
                objcon.Close();
                if (objdt.Rows.Count > 0)
                {
                    TextBox1.Text = objdt.Rows[0]["Name"].ToString();
                    TextBox2.Text = objdt.Rows[0]["Address"].ToString();
                    TextBox3.Text = objdt.Rows[0]["ContactNo"].ToString();
                }
            }
            catch
            {
                // lblmessage.Text = "Error while getting the record.";
            }
        }
        private void BindGrid()
        {
            try
            {
                DataTable objdt = new DataTable();
                string query = "select * from student;";
                SqlDataAdapter objda = new SqlDataAdapter(query, objcon);
                objcon.Open();
                objda.Fill(objdt);
                objcon.Close();
                if (objdt.Rows.Count > 0)
                {
                    griddemo.DataSource = objdt;
                    griddemo.DataBind();
                }
            }
            catch
            {
                lblmessage.Text = "Error while getting the record.";
            }
        }
        protected void DeleteRecord(string DeleteID)
        {
            try
            {
                DataTable objdt = new DataTable();
                string query = "delete from student where Id=`" + DeleteID + "`";
                SqlDataAdapter objda = new SqlDataAdapter(query, objcon);
                objcon.Open();
                objda.SelectCommand.ExecuteNonQuery();
                objcon.Close();
                Response.Redirect("WebForm1.aspx");
            }
            catch
            {
                lblmessage.Text = "Error while saving the record.";
            }
        }

        protected void griddemo_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Delete"))
            {
                GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
                Label lblid = (Label)griddemo.Rows[row.RowIndex].FindControl("lblid");
                DeleteRecord(lblid.Text);
            }
        }

    }
}


Now run the application.

manage data

INSERT

Insert record

After saving the record.

Insert record

UPDATE

UPDATE RECORD

DELETE

DELTE RECORD

PRESS OK

delete record

Thanks...


__________________________

DOWNLOAD
__________________________

No comments:

Post a Comment