Firstly, create a table in database. I have created it with Name Tester including three columns.
Id Primary Key int Not Null.
Name varchar(200)
Email varchar(100)
- Now open Visual Studio, Select File then New Project and Add New ASP.NET Web Application.
- Now in the Solutions Explorer, right click on the Application then select Add New Item, then Select Data from the left pane, Select ADO.Net Entity Model, Click Add, then select Generate From Database.
- Now click Next, then Click New Connection, Provide your Server Name to Connect to Database.
- Use SQL Server Authentication, provide your UserName and Password and select the Database Name, Click Ok. Click on Yes, include sensitive data in the connection string. A new Connection String gets added into Web.Config of your Application by DatabaseNameEntities.
- Now click Next. Now the next window comes, Choose your Database Objects and Settings that includes what Tables and StoredProcedure, Functions, Views we want to include in our Entity Model.
- Now expand the table section in that Window, it will show the List of Tables in the Database, Select our Table, you will be able to see a Table by Name Tester. elect that Table and click Finish.
- Now a Design Window appears in which Table has been Added by Name Tester.
- Also Look at Solution Explorer, there is a Model with extension .edmx, in my Case it is Employee.Edmx as I have given Name Employee while Adding ADO.NET Entity Model, Expand it and click on Employee.tt which is an Entity Template, after clicking you can see the system has created a class of type Entity Object with name Tester.cs here Tester is the Table Name.
- Just click on that Class, we can see three Properties are added, in that class Id, Name and Email which are nothing but Column Name of that Table.
- Now right click on Application and click Add New Item and dd WebForm on which we will display data from table. Writing functionality to Insert Data, Update and Delete Data from Database.
- On the WebForm include two TextBoxes for Name and Email respectively. A Hidden Field to Store Id Value, which is Primary Key. Include a GridView to bind data and two buttons: Submit and Cancel. Also two spans with chkName and chkEmail have been included which will be displayed if user enters invalid Name or Email in TextBox. The following is the code on Design Page:
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CrudEntity.WebForm1" %>
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
-
- <head runat="server">
- <script src="Scripts/jquery-1.10.2.js"></script>
- <script type="text/javascript" lang="ja">
- function ValidateName(e)
- {
- var keyCode = (e.which) ? e.which : e.keyCode
- if (((keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122)) || keyCode == 32)
- {
- document.getElementById("chkName")
- .style.display = "none";
- return true;
- }
- else
- {
- document.getElementById("chkName")
- .style.display = "inline";
- return false;
- }
- }
- </script>
- <title></title>
- </head>
-
- <body>
- <form id="form1" runat="server">
- <div>
- <table>
- <tr>
- <td> Name : </td>
- <td>
- <asp:TextBox ID="txtName" runat="server" onkeypress="return ValidateName(event);"> </asp:TextBox> <span id="chkName" style="color: Red; display: none">Name Should Not Contain Numeric Values</span> </td>
- <td> </td>
- </tr>
- <tr>
- <td> Email : </td>
- <td>
- <asp:TextBox ID="txtEmail" runat="server"> </asp:TextBox> <span id="chkEmail" style="color: Red; display: none" runat="server">Please Enter Valid Email ID</span> </td>
- </tr>
- <tr>
- <td>
- <asp:HiddenField ID="hdfId" runat="server" /> </td>
- </tr>
- <tr>
- <td>
- <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /> </td>
- <td>
- <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" /> </td>
- </tr>
- <tr>
- <td>
- <asp:GridView ID="gvDisplay" runat="server" AutoGenerateColumns="false" DataKeyNames="Id" OnPageIndexChanging="gvDisplay_PageIndexChanging" OnRowCommand="gvDisplay_RowCommand" OnRowDeleting="gvDisplay_RowDeleting" OnSelectedIndexChanging="gvDisplay_SelectedIndexChanging" AllowPaging="true" PageSize="5">
- <Columns>
- <asp:BoundField DataField="Name" HeaderText="Name" />
- <asp:BoundField DataField="Email" HeaderText="Email" />
- <asp:CommandField ButtonType="Button" SelectText="Edit" ShowSelectButton="True" />
- <asp:TemplateField>
- <ItemTemplate>
- <asp:Button runat="server" ID="btnDelete" OnClientClick="return confirm('Are you want to Delete this record?');" Text="Delete" CommandName="Delete" /> </ItemTemplate>
- </asp:TemplateField>
- </Columns>
- </asp:GridView>
- </td>
- </tr>
- </table>
- </div>
- </form>
- </body>
-
- </html>
Now the GridView gvDisplay has Property DataKeyNames which has been assigned value Id which is the Primary Key in our Table.
- Set this Property to specify field that represents Primary Key of the DataSource. This is Set to Field that are required to uniquely identify each row, it will allow automatic update and delete features of GridView Control to work. The value of this field is passed to DataSource control, in order to specify the row to Update or Delete, to retrieve the DataKey when Updating or Deleting a row use the DataKeys property of GridView.
- Now on CS side write the following code:
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data.SqlClient;
- using System.Linq;
- using System.Text.RegularExpressions;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- namespace CrudEntity
- {
- public partial class WebForm1: System.Web.UI.Page
- {
- LearningDBEntities context = new LearningDBEntities();
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!Page.IsPostBack)
- {
- gvDisplay.Visible = false;
- btnCancel.Visible = false;
- BindDisplay();
- }
- }
- private void BindDisplay()
- {
- try
- {
- if (context.Testers.Count() > 0)
- {
- var query = (from test in context.Testers select new
- {
- test.Id,
- test.Name,
- test.Email
- })
- .ToList();
- gvDisplay.DataSource = query;
- gvDisplay.DataBind();
- gvDisplay.Visible = true;
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- protected void btnSubmit_Click(object sender, EventArgs e)
- {
- try
- {
- if (CheckBlank())
- {
- ValidateEmail();
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- private bool CheckBlank()
- {
- bool flag = true;
- string message = string.Empty;
- if (txtEmail.Text == string.Empty)
- {
- message += "Please Enter Email, ";
- flag = false;
- }
- if (txtName.Text == string.Empty)
- {
- message += "Please Enter Name, ";
- flag = false;
- }
- if (message.Length > 0)
- {
- message = message.Remove(message.Length - 2);
- ShowMessage(message);
- }
- return flag;
- }
- private void ShowMessage(string Message)
- {
- try
- {
- ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Alert", "alert('" + Message + "');", true);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- private void SaveUpdate()
- {
- try
- {
- Tester test = new Tester();
- if (btnSubmit.Text.Equals("Submit"))
- {
- test.Name = txtName.Text;
- test.Email = txtEmail.Text;
- context.Testers.Add(test);
- context.SaveChanges();
- ShowMessage("Records Inserted Successfully");
- }
- if (btnSubmit.Text.Equals("Update"))
- {
- int StudentId = Convert.ToInt32(hdfId.Value);
- var singleRecord = context.Testers.First(student => student.Id == StudentId);
- singleRecord.Name = txtName.Text;
- singleRecord.Email = txtEmail.Text;
- context.SaveChanges();
- btnSubmit.Text = "Submit";
- ShowMessage("Information Updated Successfulluy");
- btnCancel.Visible = false;
- }
- BindDisplay();
- Clear();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- private void Clear()
- {
- try
- {
- txtEmail.Text = "";
- txtName.Text = "";
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- protected void gvDisplay_PageIndexChanging(object sender, GridViewPageEventArgs e)
- {
- try
- {
- gvDisplay.PageIndex = e.NewPageIndex;
- BindDisplay();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- protected void gvDisplay_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
- {
- try
- {
- int Id = Convert.ToInt32(gvDisplay.DataKeys[e.NewSelectedIndex].Value);
- hdfId.Value = Convert.ToString(Id);
- var singleRecord = context.Testers.First(student => student.Id == Id);
- txtEmail.Text = singleRecord.Email;
- txtName.Text = singleRecord.Name;
- btnSubmit.Text = "Update";
- btnCancel.Visible = true;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- protected void gvDisplay_RowCommand(object sender, GridViewCommandEventArgs e)
- {}
- protected void gvDisplay_RowDeleting(object sender, GridViewDeleteEventArgs e)
- {
- try
- {
- int Id = Convert.ToInt32(gvDisplay.DataKeys[e.RowIndex].Value);
- var singleStudent = context.Testers.First(student => student.Id == Id);
- context.Testers.Remove(singleStudent);
- context.SaveChanges();
- ShowMessage("Records Deleted Successfully");
- BindDisplay();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- protected void btnCancel_Click(object sender, EventArgs e)
- {
- try
- {
- btnSubmit.Text = "Submit";
- BindDisplay();
- btnCancel.Visible = false;
- Clear();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- private void ValidateEmail()
- {
- try
- {
- string email = txtEmail.Text;
- Regex regex = new Regex(@ "^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
- Match match = regex.Match(email);
- if (!match.Success)
- {
- chkEmail.Style["display"] = "inline";
- }
- else
- {
- chkEmail.Style["display"] = "none";
- SaveUpdate();
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- }
- }
As you can see the events of GridView: SelectedIndexChanging, RowDeleting, RowCommand, PageIndexChanging. You can see the line:
- int Id = Convert.ToInt32(gvDisplay.DataKeys[e.NewSelectedIndex].Value);
Here, DataKeys property is been used which gives the Id of respective record.
Also, there is a method for saving and updating the data which is SaveUpdate, there is a method ValidateEmail to validate email which is been called on Submit button click. There is a method BindDisplay, which binds the GridView.
A object has been created of LearningDBEntities; LearningDBEntities is a DBContext class where LearningDB is my database name. This is a class derived From DbContext Class.DbContext class is the Primary Class which is responsible for Interacting with data. Also I have created object of Tester Class, Tester is our table name.
- Tester test = new Tester();
See this line inside SaveUpdate Method,using this we can access properties of Tester Class, which are nothing but column names. Also on saving the data, method used is Add to which we passed the Object test which includes values assigned to columns in the Table. For Delete method is Remove and SaveChanges is been used to save changes in the database.
I will come with more details about Entity Framework in next article. If anything is missing, please let me know about it in the comments section.