Donate

ASP.NET FormView CRUD With Entity Framework

Most of the examples on FormView Web Server control use DataSource wizard controls such as SqlDatasource or ObjectDataSource when assigning value to the FormView's DataSource property.
However, using those controls have drawbacks such as maintainability. I also found samples out there using ADO.NET. Enough with the chit-chat and let's proceed with coding. I'll post the create table statement, code behind and the aspx markup.

SQL Code:
USE [Books]
GO
 
SET ANSI_NULLS ON
GO
 
SET QUOTED_IDENTIFIER ON
GO
 
SET ANSI_PADDING ON
GO
 
CREATE TABLE [dbo].[BookDetails](
    [BookSerialNo] [int] IDENTITY(1,1) NOT NULL,
    [BookISBN] [nchar](15) NULL,
    [BookTitle] [varchar](120) NULL,
    [BookAuthor] [varchar](60) NULL,
    [BookPublisher] [varchar](50) NULL,
    [BookCategory] [varchar](20) NULL,
PRIMARY KEY CLUSTERED 
(
    [BookSerialNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) 
  ON [PRIMARY]
) ON [PRIMARY]
 
GO
CodeBehind:
public partial class FormViewDemo : System.Web.UI.Page
    {
        private BooksEntities _context;
 
        public FormViewDemo()
        {
            _context = new BooksEntities();
        }
 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindFormView();
            }
        }
 
        private void BindFormView()
        {
            var bookRecords = _context.BookDetails.ToList();
            FormViewBookDetails.DataSource = bookRecords;
            FormViewBookDetails.DataBind();
        }
 
        protected void FormViewBookDetails_ItemCommand(object sender, FormViewCommandEventArgs e)
        {
            if (e.CommandName == "Cancel")
            {
                FormViewBookDetails.ChangeMode(FormViewMode.ReadOnly);
            }
            else if (e.CommandName == "Edit")
            {
                FormViewBookDetails.ChangeMode(FormViewMode.Edit);
            }
            else if (e.CommandName == "New")
            {
                FormViewBookDetails.ChangeMode(FormViewMode.Insert);
            }
            else if (e.CommandName == "Delete")
            {
                FormViewBookDetails.ChangeMode(FormViewMode.ReadOnly);
                BindFormView();
            }
        }
        
        protected void FormViewBookDetails_PageIndexChanging(object sender, FormViewPageEventArgs e)
        {
            FormViewBookDetails.PageIndex = e.NewPageIndex;
            BindFormView();
        }
 
        protected void FormViewBookDetails_ModeChanging(object sender, FormViewModeEventArgs e)
        {
            if (e.NewMode == FormViewMode.Insert)
            {
                FormViewBookDetails.AllowPaging = false;
            }
            else if (e.NewMode == FormViewMode.Edit)
            {
                FormViewBookDetails.AllowPaging = false;
                BindFormView();
            }
            else
            {
                FormViewBookDetails.AllowPaging = true;
                BindFormView();
            }
        }
 
        protected void FormViewBookDetails_ItemInserting(object sender, FormViewInsertEventArgs e)
        {
            var item = new BookDetail();
            item.BookISBN = ((TextBox)FormViewBookDetails.FindControl("txtInsertBookISBN")).Text;
            item.BookTitle = ((TextBox)FormViewBookDetails.FindControl("txtInsertBookTitle")).Text;
            item.BookAuthor = ((TextBox)FormViewBookDetails.FindControl("txtInsertBookAuthor")).Text;
            item.BookPublisher = ((TextBox)FormViewBookDetails.FindControl("txtInsertBookPublisher")).Text;
            item.BookCategory = ((TextBox)FormViewBookDetails.FindControl("txtInsertBookCategory")).Text;
            _context.BookDetails.Add(item);
            _context.SaveChanges();
            ResetBinding();
        }
 
        protected void FormViewBookDetails_ItemUpdating(object sender, FormViewUpdateEventArgs e)
        {
            int id = Int32.Parse(FormViewBookDetails.DataKey[0].ToString());
            var result = _context.BookDetails.Find(id);
            if (result != null)
            {
                var item = new BookDetail();
                item.BookSerialNo = id;
                item.BookISBN = ((TextBox)FormViewBookDetails.FindControl("txtBookISBN")).Text;
                item.BookTitle = ((TextBox)FormViewBookDetails.FindControl("txtBookTitle")).Text;
                item.BookAuthor = ((TextBox)FormViewBookDetails.FindControl("txtBookAuthor")).Text;
                item.BookPublisher = ((TextBox)FormViewBookDetails.FindControl("txtBookPublisher")).Text;
                item.BookCategory = ((TextBox)FormViewBookDetails.FindControl("txtBookCategory")).Text;
                _context.Entry(result).CurrentValues.SetValues(item);
                _context.SaveChanges();
                ResetBinding();
            }
        }
 
        private void ResetBinding()
        {
            FormViewBookDetails.ChangeMode(FormViewMode.ReadOnly);
            FormViewBookDetails.AllowPaging = true;
            BindFormView();
        }
 
        protected void FormViewBookDetails_ItemDeleting(object sender, FormViewDeleteEventArgs e)
        {
            if (FormViewBookDetails.DataKey[0] != null)
            {
                var id = Int32.Parse(FormViewBookDetails.DataKey[0].ToString());
                var itemDelete = _context.BookDetails.FirstOrDefault(t => t.BookSerialNo == id);
                if (itemDelete != null)
                {
                    _context.Entry(itemDelete).State = EntityState.Deleted;
                    _context.SaveChanges();
                    ResetBinding();
                }
            }
        }
    }
ASPX Markup:
<asp:FormView ID="FormViewBookDetails" runat="server" AllowPaging="True" DataKeyNames="BookSerialNo" GridLines="Both" ClientIDMode="Static"
      OnItemCommand="FormViewBookDetails_ItemCommand" OnPageIndexChanging="FormViewBookDetails_PageIndexChanging" 
      OnModeChanging="FormViewBookDetails_ModeChanging" OnItemInserting="FormViewBookDetails_ItemInserting" 
      OnItemDeleting="FormViewBookDetails_ItemDeleting" PagerSettings-Mode="NumericFirstLast" OnItemUpdating="FormViewBookDetails_ItemUpdating">
      <headertemplate>
          <table class="" id="tblHeader">
            <tr>
              <td colspan="2">
                  <div id="Header">
                      <asp:label id="lbl" Text="GHK Bookshop FormView Create-Update-Delete Demo" runat="server"/> 
                  </div>                                            
              </td>
            </tr>
          </table>
    </headertemplate>
    <EditItemTemplate>
        <table id="tblEdit">
            <tr>
                <td >Serial # : </td>
                <td>
                    <asp:Label ID="lblBookSerialNo" runat="server" Text='<%# Eval("BookSerialNo") %>' />
                </td>
            </tr>
            <tr>
                <td >ISBN : </td>
                <td>
                    <asp:TextBox ID="txtBookISBN" runat="server" required="required"  Text='<%# Bind("BookISBN") %>'></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td >Title : </td>
                <td>
                    <asp:TextBox ID="txtBookTitle" runat="server"  required="required"   Text='<%# Bind("BookTitle") %>'></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td >Author : </td>
                <td>
                    <asp:TextBox ID="txtBookAuthor" runat="server"   required="required"  Text='<%# Bind("BookAuthor") %>'></asp:TextBox>
                </td>
            </tr>
            <tr>
               <td >Publisher : </td>
                <td>
                    <asp:TextBox ID="txtBookPublisher" runat="server"  required="required"   Text='<%# Bind("BookPublisher") %>'></asp:TextBox>
                </td>
            </tr>
            <tr>
               <td >Category : </td>
                <td>
                    <asp:TextBox ID="txtBookCategory" runat="server"  required="required"   Text='<%# Bind("BookCategory") %>'></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnUpdate" runat="server" CommandName="Update" Text="Update" />
                    <asp:Button ID="btnCancel" runat="server" CommandName="Cancel" Text="Cancel" UseSubmitBehavior="false" CausesValidation="false"/>
                </td>
            </tr>
        </table>
    </EditItemTemplate>
    <ItemTemplate>
        <table id="tblItem">
            <tr>
                <td>Serial # : </td>
                <td>
                    <asp:Label ID="EmployeeIDLabel" runat="server" Text='<%# Eval("BookSerialNo") %>' />
                </td>
            </tr>
            <tr>
                <td >ISBN : </td>
                <td>
                    <asp:Label ID="LastNameLabel" runat="server" Text='<%# Bind("BookISBN") %>' />
                </td>
            </tr>
            <tr>
                <td >Title : </td>
                <td>
                    <asp:Label ID="FirstNameLabel" runat="server" Text='<%# Bind("BookTitle") %>' />
                </td>
            </tr>
            <tr>
                <td >Author : </td>
                <td>
                    <asp:Label ID="CountryLabel" runat="server" Text='<%# Bind("BookAuthor") %>' />
                </td>
            </tr>
            <tr>
                <td>Publisher :</td>
                <td>
                    <asp:Label ID="NotesLabel" runat="server" Text='<%# Bind("BookPublisher") %>' />
                </td>
            </tr>
            <tr>
                <td>Category :</td>
                <td>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("BookCategory") %>' />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnInsert" runat="server" Text="Add" CommandName="New" />
                    <asp:Button ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" UseSubmitBehavior="false"/>                        
                    <asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" />
                </td>
            </tr>
        </table>
    </ItemTemplate>
    <InsertItemTemplate>
          <table id="tblInsert">
            <tr>
                <td >ISBN : </td>
                <td>
                    <asp:TextBox ID="txtInsertBookISBN"  required="required" runat="server" Text='<%# Bind("BookISBN") %>'></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td >Title : </td>
                <td>
                    <asp:TextBox ID="txtInsertBookTitle" required="required"  runat="server" Text='<%# Bind("BookTitle") %>'></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td >Author : </td>
                <td>
                    <asp:TextBox ID="txtInsertBookAuthor" required="required"  runat="server" Text='<%# Bind("BookAuthor") %>'></asp:TextBox>
                </td>
            </tr>
            <tr>
               <td >Publisher : </td>
                <td>
                    <asp:TextBox ID="txtInsertBookPublisher" required="required"  runat="server" Text='<%# Bind("BookPublisher") %>'></asp:TextBox>
                </td>
            </tr>
            <tr>
               <td >Category : </td>
                <td>
                    <asp:TextBox ID="txtInsertBookCategory" required="required"  runat="server" Text='<%# Bind("BookCategory") %>'></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnSave" runat="server" CommandName="Insert" Text="Save"/>
                    <asp:Button ID="btnCancelInsert" runat="server" CommandName="Cancel" Text="Cancel"   UseSubmitBehavior="false" CausesValidation="false" />
                </td>
            </tr>
        </table>
    </InsertItemTemplate>
</asp:FormView>    
When creating this project, add an Ado.Net Entity Data Model which points to the specified database. :-)

Sample screenshots (Create, Details, Update)
ASP.NET FormView CRUD With Entity Framework
ASP.NET FormView CRUD With Entity Framework
ASP.NET FormView CRUD With Entity Framework

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.