CREATE READ UPDATE and DELETE - CRUD operations using Entity Framework 4

Unknown | 9:30 PM |



<table width="80%" cellspacing="1" cellpadding="5" style="background: #ccc">

    <tr style="background: #fff">

        <td colspan="2">

            <strong>Student Management</strong>

        </td>

    </tr>

    <tr style="background: #fff">

        <td colspan="2">

            <asp:Label ID="statusLabel" runat="server" Text="" ForeColor="Red">

            </asp:Label>

        </td>

    </tr>

    <tr style="background: #fff">

        <td colspan="2">

            <asp:GridView ID="grid"

                          runat="server"

                          DataKeyNames="StudentId"                                           

                          OnSelectedIndexChanging="grid_SelectedIndexChanging"

                          OnRowDeleting="grid_RowDeleting"

                          AutoGenerateColumns="false"

                          Width="100%">

            <Columns>

                <asp:TemplateField>

                    <HeaderTemplate>

                        <table width="100%" cellpadding="5" cellspacing="1">

                            <tr>

                                <td align="center" style="width: 5%;">

                                    nbsp;                                 

                                </td>

                                <td align="center" style="width: 5%;">

                                    &nbsp;

                                </td>

                                <td align="left" style="width: 15%">

                                    Name

                                </td>

                                <td align="left" style="width: 15%">

                                    Address

                                </td>

                                <td align="left" style="width: 15%">

                                    Birthdate

                                </td>

                                <td align="left" style="width: 10%">

                                    Photo

                                </td>

                                <td align="left" style="width: 20%">

                                    Email

                                </td>

                                <td align="left" style="width: 15%">

                                    Mobile

                                </td>

                            </tr>

                        </table>

                    </HeaderTemplate>

                    <ItemTemplate>

                        <table width="100%" cellpadding="0" cellspacing="1">

                            <tr>

                                <td align="center" style="width: 5%;">

                                    <asp:ImageButton ID="ImageButton1"

                                                    runat="server"                                                                                CommandName="Select"

                                                     EnableTheming="false"

                                                     ImageUrl="~/Images/edit.png"
                                                    
                                                     AlternateText="Edit"

                                                     CausesValidation="false" />

                                </td>

                                <td align="center" style="width: 5%;">

                                    <asp:ImageButton ID="LinkButton2"

                                                     runat="server"

                                                      ImageUrl="~/Images/delete.png"

                                                      AlternateText="Delete"

                                                     CommandName="Delete"

                                                       EnableTheming="false"

                                                     CausesValidation="false" />

                                </td>

                                <td align="left" style="width: 15%">

                                    <asp:Label ID="lblName" runat="server"

                                              Text='<%# Eval("Name")%>'></asp:Label>

                                </td>

                                <td align="left" style="width: 15%">

                                    <asp:Label ID="lblAddress" runat="server"

                                              Text='<%# Eval("Address")%>'></asp:Label>

                                </td>

                                <td align="center" style="width: 15%">

                                    <asp:Label ID="lblBirthdate" runat="server"

                                             Text='<%# Eval("Birthdate")%>'></asp:Label>

                                </td>

                                <td align="center" style="width: 10%">

                                    <asp:Image ID="imgPhoto" runat="server" Width="30"                                           Height="30"

                                        ImageUrl='<%# "~/Images/" + Eval("Image")%>' />

                                </td>

                                <td align="left" style="width: 20%">

                                    <asp:Label ID="lblEmail" runat="server"

                                              Text='<%# Eval("Email")%>'></asp:Label>

                                </td>

                                <td align="left" style="width: 15%">

                                    <asp:Label ID="lblMobile" runat="server"

                                              Text='<%# Eval("Mobile")%>'></asp:Label>

                                </td>

                            </tr>

                        </table>

                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

        </asp:GridView>

    </td>

</tr>

<tr style="background: #fff">

    <td>

        Name<asp:HiddenField ID="hdnId" runat="server" />

    </td>

    <td>

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

    </td>

</tr>

<tr style="background: #fff">

    <td>

        Address

    </td>

    <td>

        <asp:TextBox ID="txtAddress" runat="server" TextMode="MultiLine"></asp:TextBox>

    </td>

</tr>

<tr style="background: #fff">

    <td>

        Birthdate

    </td>

    <td>

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

        <asp:Calendar ID="calBirthdate" runat="server" 

                      OnSelectionChanged="calBirthdate_SelectionChanged">

        </asp:Calendar>

    </td>

</tr>

<tr style="background: #fff">

    <td>

        Image

    </td>

    <td>

        <asp:Image ID="imgThumb" runat="server" Width="100" Height="100" />

        <asp:FileUpload ID="fupImage" runat="server" />

    </td>

</tr>

<tr style="background: #fff">

    <td>

        Email

    </td>

    <td>

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

    </td>

</tr>

<tr style="background: #fff">

    <td>

        Mobile

    </td>

    <td>

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

    </td>

</tr>

<tr style="background: #fff">

    <td>

        Description

    </td>

    <td>

        <asp:TextBox ID="txtDescription" runat="server" TextMode="MultiLine">

        </asp:TextBox>

    </td>

</tr>

<tr style="background: #fff">

    <td>

        &nbsp;

    </td>

    <td>

        <asp:Button ID="btnAdd" ValidationGroup="add" OnClick="btnAdd_Click"                               runat="server" Text="Submit">

        </asp:Button>

        <asp:Button ID="btnReset" OnClick="btnReset_Click" runat="server"                                        CausesValidation="false" Text="Reset">

        </asp:Button>

        <asp:Button ID="btnUpdate" ValidationGroup="add" OnClick="btnUpdate_Click"                            runat="server" Text="Update">

        </asp:Button>

        <asp:Button ID="btnCancel" CausesValidation="false" OnClick="btnCancel_Click"                      runat="server" Text="Cancel">

        </asp:Button>

    </td>

</tr>

</table>


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.Configuration;

using System.IO;

namespace LinqSamples
{
    public partial class WebForm4 : System.Web.UI.Page
    {
        //StudentDbDataContext SDC = new StudentDbDataContext();
        TMSMASTEREntities1 SDC = new TMSMASTEREntities1();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                btnUpdate.Visible = false;

                btnCancel.Visible = false;

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



                BindGrid();

                checkMax();

                bindDDL();

            }

        }
        private void BindGrid()
        {
            var students = from student in SDC.Students

                           select new {
                               student.StudentId,
                               student.Name,
                               student.Address,
                               student.BirthDate,
                               student.Image,
                               student.Email,
                               student.Mobile,
                               student.Description
                           };

            grid.DataSource = students;
            grid.DataBind();

        }



        protected void grid_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {

            btnAdd.Visible = false;

            btnReset.Visible = false;

            btnUpdate.Visible = true;

            btnCancel.Visible = true;



            int id =Convert.ToInt32( grid.DataKeys[e.NewSelectedIndex].Value.ToString());

            hdnId.Value = id.ToString();



            //SDC = new StudentDbDataContext();
            SDC = new TMSMASTEREntities1();

            var singleStudent = SDC.Students.Single(student => student.StudentId == id);

         

            txtName.Text = singleStudent.Name;

            txtAddress.Text = singleStudent.Address;

            txtBirthdate.Text = singleStudent.BirthDate.ToString();

            imgThumb.ImageUrl = "~//images//" + singleStudent.Image;

            imgThumb.Visible = true;

            txtEmail.Text = singleStudent.Email;

            txtMobile.Text = singleStudent.Mobile.ToString();

            txtDescription.Text = singleStudent.Description;



        }



        protected void btnAdd_Click(object sender, EventArgs e)
        {

            try
            {

                //SDC = new StudentDbDataContext();
                SDC = new TMSMASTEREntities1();
                Student student = new Student();



                student.Name = txtName.Text;

                student.Address = txtAddress.Text;

                student.BirthDate = Convert.ToDateTime(txtBirthdate.Text);

                if (fupImage.HasFile)
                {

                    student.Image = fupImage.FileName;

                    string path = Server.MapPath(".") + "\\images\\";

                    fupImage.SaveAs(path + fupImage.FileName);

                }

                student.Email = txtEmail.Text;

                student.Mobile = Convert.ToInt64(txtMobile.Text);

                student.Description = txtDescription.Text;



                //SDC.Students.InsertOnSubmit(student);

                //SDC.SubmitChanges();

                SDC.AddToStudents(student);
              
              
                SDC.SaveChanges();
             

                ClearControls();

                statusLabel.Text = "Record Inserted Successfully.";

            }

            catch (Exception Err)
            {

                statusLabel.Text = Err.Message;

            }



            BindGrid();

        }



        protected void btnReset_Click(object sender, EventArgs e)
        {

            ClearControls();

        }



        protected void btnCancel_Click(object sender, EventArgs e)
        {

            ClearControls();



            btnAdd.Visible = true;

            btnReset.Visible = true;

            btnUpdate.Visible = false;

            btnCancel.Visible = false;

        }



        protected void btnUpdate_Click(object sender, EventArgs e)
        {

            try
            {

                //SDC = new StudentDbDataContext();
                int Id=Convert.ToInt32(hdnId.Value);

                SDC = new TMSMASTEREntities1();

                var singleStudent = SDC.Students.Single(student => student.StudentId == Id);

                string ImageName = singleStudent.Image;

                string path = Server.MapPath(".") + "\\images\\";



                singleStudent.Name = txtName.Text;

                singleStudent.Address = txtAddress.Text;

                singleStudent.BirthDate = Convert.ToDateTime(txtBirthdate.Text);



                if (fupImage.HasFile)
                {

                    if (File.Exists(path + ImageName))

                        File.Delete(path + ImageName);



                    ImageName = fupImage.FileName;



                    fupImage.SaveAs(path + ImageName);



                    singleStudent.Image = ImageName;

                }



                singleStudent.Email = txtEmail.Text;

                singleStudent.Mobile = Convert.ToInt64(txtMobile.Text);

                singleStudent.Description = txtDescription.Text;

                //SDC.SubmitChanges();
           
                SDC.SaveChanges();

                ClearControls();

                statusLabel.Text = "Record Inserted Successfully.";



                btnAdd.Visible = true;

                btnReset.Visible = true;

                btnUpdate.Visible = false;

                btnCancel.Visible = false;

            }

            catch (Exception Err)
            {

                statusLabel.Text = Err.Message;

            }



            BindGrid();

        }



        protected void grid_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

            int id =Convert.ToInt32( grid.DataKeys[e.RowIndex].Value.ToString());



            //StudentDbDataContext SDC = new StudentDbDataContext();
            TMSMASTEREntities1 SDC = new TMSMASTEREntities1();

            var singleStudent = SDC.Students.Single(student => student.StudentId == id);



            string path = Server.MapPath(".") + "\\images\\";

            if (File.Exists(path + singleStudent.Image))
            {

                File.Delete(path + singleStudent.Image);

            }



            //SDC.Students.DeleteOnSubmit(singleStudent);

            //SDC.SubmitChanges();

            SDC.DeleteObject(singleStudent);

            SDC.SaveChanges();

            BindGrid();

        }



        private void ClearControls()
        {

            txtName.Text = string.Empty;

            txtAddress.Text = string.Empty;

            txtEmail.Text = string.Empty;

            txtMobile.Text = string.Empty;

            txtDescription.Text = string.Empty;

            txtBirthdate.Text = string.Empty;

            imgThumb.Visible = false;

        }

        public void checkMax()
        {
            int? maxEmpID = SDC.Students.Max(q => (int?)q.StudentId) ;

            int? ID = (from n in SDC.Students
                         where n.Name == "fgh"
                      select (int?)n.StudentId).Max<int?>();

            if (maxEmpID != null)
            {
                maxEmpID = maxEmpID + 1;
                hdnId.Value = maxEmpID.ToString();
            }
            else
            {
                maxEmpID = 1000;
                hdnId.Value = maxEmpID.ToString();
            }
        }

        public void bindDDL()
        {
            var display = from e in SDC.Students select new { e.StudentId };

            ddlStudentID.DataSource = display.ToList();
            ddlStudentID.DataTextField = "StudentId";
            ddlStudentID.DataValueField = "StudentId";
            ddlStudentID.DataBind();
            ddlStudentID.Items.Insert(0, "--Select--");

        
        }

        protected void calBirthdate_SelectionChanged(object sender, EventArgs e)
        {

            txtBirthdate.Text = calBirthdate.SelectedDate.ToShortDateString();

        }

        protected void ddlStudentID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlStudentID.SelectedItem.Text != "--Select--")
            {

                int id = Convert.ToInt16(ddlStudentID.SelectedValue.ToString());

                var display = from student in SDC.Students

                              where student.StudentId.Equals(id)

                              select new
                              {
                                  student.StudentId,
                                  student.Name,
                                  student.Address,
                                  student.BirthDate,
                                  student.Image,
                                  student.Email,
                                  student.Mobile,
                                  student.Description
                              };



                foreach (var v in display)
                {

                    txtName.Text = v.Name;

                    txtAddress.Text = v.Address;

                    txtBirthdate.Text = v.BirthDate.ToString();

                    imgThumb.ImageUrl = "~//images//" + v.Image;

                    imgThumb.Visible = true;

                    txtEmail.Text = v.Email;

                    txtMobile.Text = v.Mobile.ToString();

                    txtDescription.Text = v.Description;

                }

            }
        }
    }
}

Category:

About http://dotnetvisual.blogspot.in/:
DOT NET TO ASP.NET is a web application framework marketed by Microsoft that programmers can use to build dynamic web sites, web applications and web services. It is part of Microsoft's .NET platform and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime, allowing programmers to write ASP.NET code using any Microsoft .NET language. create an application very easily ....