Saturday 25 February 2023

CURD (Create Update Retrieve Delete) Operations Using form view in asp.net

 Agenda :

            Dear all In this article, we will discuss CURD(Create Update Retrieve Delete) Operations Using Form View in Asp.Net

Description :

          In previous articles, I have explained Must Avoid Mistakes using Date Time in C#MS Sql Server Row_Number() Interview Question 2023How to work with File upload control using Asp.Net – PART - IWorking with File Upload control using Asp.Net – PART - IIHow to resolve maximum requested length exceeded error with file upload control – PART - III different articles related to C#.Net,Asp.NetSQL ServerXML, and DotNetInterviewQuestions Related articles. Now Let's work on CURD(Create Update Retrieve Delete) Operations Using Form View in Asp.Net




Steps to work with this:

  1. Go To Visual Studio Click on New Website
  2. ClickOnAsp.Net Empty Website(Or choose any web template)Click Ok
  3. Drag and drop the form view control
  4. Implement the code as per the demonstration
Video Explanation:

Database Script:

CREATE TABLE tbl_Departments(ID INT IDENTITY,

Code VARCHAR(50),Name VARCHAR(100),Location VARCHAR(100),IsACtive BIT,

CreatedOn DATETIME,CreatedBy VARCHAR(100),ModifiedOn DATETIME,ModifiedBy VARCHAR(100)) 

INSERT INTO tbl_Departments(Code,Name,Location,IsACtive,CreatedBy,CreatedOn) VALUES('TECH','Technical','Hyderabad',1,'Admin',GETDATE())

 SELECT *FROM tbl_Departments


.aspx Code (Source or Design Code):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="P1.aspx.cs" Inherits="FormView_Ex_2023_0226.P1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <asp:FormView ID="fvDeptData" runat="server" DataKeyNames="ID" AllowPaging="True" OnItemCommand="fvDeptData_ItemCommand" OnItemDeleting="fvDeptData_ItemDeleting" OnItemInserting="fvDeptData_ItemInserting" OnItemUpdating="fvDeptData_ItemUpdating" OnModeChanging="fvDeptData_ModeChanging" OnPageIndexChanging="fvDeptData_PageIndexChanging">

                <ItemTemplate>

                    <table border="1" align="center" width="80%">

                        <tr>

                            <td>Code</td>

                            <td><%#Eval("Code") %> </td>

                        </tr>

                        <tr>

                            <td>Name</td>

                            <td><%#Eval("Name") %> </td>

                        </tr>

                        <tr>

                            <td>Location</td>

                            <td><%#Eval("Location") %> </td>

                        </tr>

                        <tr>

                            <td>CreatedBy</td>

                            <td><%#Eval("CreatedBy") %> </td>

                        </tr>

                        <tr>

                            <td colspan="2">

                                <asp:LinkButton ID="lnkNew" Text="New" runat="server" CommandName="New"></asp:LinkButton>

                                &nbsp;&nbsp;<asp:LinkButton ID="lnkEdit" Text="Edit" runat="server" CommandName="Edit"></asp:LinkButton>

                                &nbsp;&nbsp;<asp:LinkButton ID="lnkDelete" Text="Delete" runat="server" CommandName="Delete"></asp:LinkButton>

                            </td>

                        </tr>

                    </table>

                </ItemTemplate>

                <InsertItemTemplate>

                    <table border="1" align="center" width="80%">

                        <tr>

                            <td>Enter Code : </td>

                            <td>

                                <asp:TextBox ID="txtICode" runat="server"></asp:TextBox>

                            </td>

                            <td>Enter Name : </td>

                            <td>

                                <asp:TextBox ID="txtIName" runat="server"></asp:TextBox>

                            </td>

                            <td>Enter Location : </td>

                            <td>

                                <asp:TextBox ID="txtILocation" runat="server"></asp:TextBox>

                            </td>

                            <td>Enter CreatedBy : </td>

                            <td>

                                <asp:TextBox ID="txtICreatedBy" runat="server"></asp:TextBox>

                            </td>

                        </tr>

                        <tr>

                            <td colspan="2">

                                <asp:LinkButton ID="lnkInsert" Text="Insert" runat="server" CommandName="Insert"></asp:LinkButton>

                                &nbsp;&nbsp;<asp:LinkButton ID="lnkCancelInsert" Text="Cancel" runat="server" CommandName="Cancel"></asp:LinkButton>

                            </td>

                        </tr>

                    </table>

                </InsertItemTemplate>

                <EditItemTemplate>

                    <table border="1" align="center" width="80%">

                        <tr>

                            <td>Code : </td>

                            <td>

                                <asp:TextBox ID="txtECode" runat="server" Text='<%#Eval("Code") %>'></asp:TextBox>

                            </td>

                            <td>Name : </td>

                            <td>

                                <asp:TextBox ID="txtEName" runat="server" Text='<%#Eval("Name") %>'></asp:TextBox>

                            </td>

                            <td>Location : </td>

                            <td>

                                <asp:TextBox ID="txtELocation" runat="server" Text='<%#Eval("Location") %>'></asp:TextBox>

                            </td>

                            <td>Enter CreatedBy : </td>

                            <td>

                                <asp:TextBox ID="txtECreatedBy" runat="server" Text='<%#Eval("CreatedBy") %>'></asp:TextBox>

                            </td>

                        </tr>

                        <tr>

                            <td colspan="2">

                                <asp:LinkButton ID="lnkUpdate" Text="Update" runat="server" CommandName="Update"></asp:LinkButton>

                                &nbsp;&nbsp;<asp:LinkButton ID="lnkCancelUpdate" Text="Cancel" runat="server" CommandName="Cancel"></asp:LinkButton>

                            </td>

                        </tr>

                    </table>

                </EditItemTemplate>

            </asp:FormView>

        </div>

    </form>

</body>

</html> 


.aspx,cs Code (Code Behind):

using System;

using System.Collections.Generic;

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

namespace FormView_Ex_2023_0226

{

    public partial class P1 : System.Web.UI.Page

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString());

        SqlCommand cmd;

        SqlDataAdapter da;

        DataSet ds;

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

                BindData();

        }

        public void BindData()

        {

            da = new SqlDataAdapter("Select *from tbl_Departments", con);

            ds = new DataSet();

            da.Fill(ds);

            fvDeptData.DataSource = ds;

            fvDeptData.DataBind();

        }

        protected void fvDeptData_ItemCommand(object sender, FormViewCommandEventArgs e)

        {

            if (e.CommandName == "Cancel")

            {

                fvDeptData.ChangeMode(FormViewMode.ReadOnly);

            }

            else if (e.CommandName == "Edit")

            {

                fvDeptData.ChangeMode(FormViewMode.Edit);

            }

            else if (e.CommandName == "New")

            {

                fvDeptData.ChangeMode(FormViewMode.Insert);

            }

            else if (e.CommandName == "Delete")

            {

                fvDeptData.ChangeMode(FormViewMode.ReadOnly);

                BindData();

            }

        }

        protected void fvDeptData_ItemDeleting(object sender, FormViewDeleteEventArgs e)

        {

            DataKey key = fvDeptData.DataKey;

            con.Open();

            cmd = new SqlCommand("Delete from tbl_Departments Where Id='"+key.Value+"'", con);

            int res = cmd.ExecuteNonQuery();

            con.Close();

            if (res > 0)

            {

                Response.Write("<script>alert('Data Deleted Successfully...')</script>");

            }

            else

            {

                Response.Write("<script>alert('Data Not Deleted.Please try again after some time...')</script>");

            }

            BindData();

        }

        protected void fvDeptData_ItemInserting(object sender, FormViewInsertEventArgs e)

        {

            TextBox txtCode = (TextBox)fvDeptData.FindControl("txtICode");

            TextBox txtName = (TextBox)fvDeptData.FindControl("txtIName");

            TextBox txtLocation = (TextBox)fvDeptData.FindControl("txtILocation");

            TextBox txtCreateBy = (TextBox)fvDeptData.FindControl("txtICreatedBy");

            con.Open();

            cmd = new SqlCommand("INSERT INTO tbl_Departments(Code,Name,Location,IsACtive,CreatedBy,CreatedOn) VALUES('" + txtCode.Text + "','" + txtName.Text + "','" + txtLocation.Text + "','1','" + txtCreateBy.Text + "',GETDATE())", con);

            int res = cmd.ExecuteNonQuery();

            con.Close();

            if (res > 0)

            {

                Response.Write("<script>alert('Data Inserted Successfully...')</script>");

            }

            else

            {

                Response.Write("<script>alert('Data Not Inserted.Please try again after some time...')</script>");

            }

            BindData();

        }

        protected void fvDeptData_ItemUpdating(object sender, FormViewUpdateEventArgs e)

        {

            DataKey key = fvDeptData.DataKey;

            TextBox txtCode = (TextBox)fvDeptData.FindControl("txtECode");

            TextBox txtName = (TextBox)fvDeptData.FindControl("txtEName");

            TextBox txtLocation = (TextBox)fvDeptData.FindControl("txtELocation");

            TextBox txtCreateBy = (TextBox)fvDeptData.FindControl("txtECreatedBy");

            con.Open();

            cmd = new SqlCommand("UPDATE tbl_Departments SET Code='" + txtCode.Text + "',Name='" + txtName.Text + "',Location='" + txtLocation.Text + "',ModifiedBy='" + txtCreateBy.Text + "',ModifiedOn=GETDATE() WHERE Id='"+key.Value+"'", con);

            int res = cmd.ExecuteNonQuery();

            con.Close();

            if (res > 0)

            {

                Response.Write("<script>alert('Data Updated Successfully...')</script>");

            }

            else

            {

                Response.Write("<script>alert('Data Not Updated.Please try again after some time...')</script>");

            }

            fvDeptData.ChangeMode(FormViewMode.ReadOnly);

            BindData();

        }

        protected void fvDeptData_ModeChanging(object sender, FormViewModeEventArgs e)

        {

            fvDeptData.ChangeMode(e.NewMode);

            BindData();

        }

        protected void fvDeptData_PageIndexChanging(object sender, FormViewPageEventArgs e)

        {

            fvDeptData.PageIndex = e.NewPageIndex;

            BindData();

        }

    }

}



No comments :

Post a Comment