Shalvin Interests

Monday, August 24, 2015

Web Forms Contact Management with Entity Framework

We are going to revisit the Contact Management System in Web Forms with Entity Framework. The details of Contact Management is taken up in this blog. There are basically two tables, viz. ContactGroups and  Contacts.

I am using Asp .Net Web Forms Site so that there will be inbuilt Master Page.

I am using Entity Framework,  Generate from Database option, the details I have blogged here.

I  the Default.aspx I am using a GridView to display the Group details.

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
   
</asp:Content>

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <p>
        <a href="InsertGroup.aspx">Insert Group</a> <a href="EditDeleteGroups.aspx">Edit/Delete Groups</a>&nbsp;</p>
<p>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundField DataField="GroupName" HeaderText="Group Name" />
        </Columns>
    </asp:GridView>
    <br />
</p>
    </asp:Content>

 ContactManagementEntities ctx = new ContactManagementEntities();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = ctx.ContactGroups.ToList();
            DataBind();

        }
    }



Inserting Records to Parent Table


<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" Runat="Server">
    <p>
        <asp:Label ID="lblMessage" runat="server"></asp:Label>
        <br />
        <asp:Label ID="Label1" runat="server" Text="Group Name"></asp:Label>
        <asp:TextBox ID="txtGroupName" runat="server"></asp:TextBox>
    </p>
    <p>
        <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" />
    </p>
</asp:Content>


public partial class InsertGroup : System.Web.UI.Page
{
    ContactManagementEntities ctx = new ContactManagementEntities();

   
    protected void btnSave_Click(object sender, EventArgs e)
    {
        var c = (from p in ctx.ContactGroups
                 where p.GroupName == txtGroupName.Text
                 select p).Count();
       
        if (c != 0)
        {
            lblMessage.Text = "Value already exist";
            txtGroupName.Text = "";
            txtGroupName.Focus();
        }
        else
        {

            ContactGroup cg = new ContactGroup { GroupName = txtGroupName.Text };
            ctx.ContactGroups.Add(cg);
            ctx.SaveChanges();
            Response.Redirect("default.aspx");
           
        }
    }
}

Here I am checking for uniqueness of entered value.


Edit and Delete Contact Groups


<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" Runat="Server">
    <p>
        <br />
        Select Group
        <asp:DropDownList ID="ddlGroup" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlGroup_SelectedIndexChanged">
        </asp:DropDownList>
    </p>
    <p>
        Group Name<asp:TextBox ID="txtGroupName" runat="server"></asp:TextBox>
    </p>
    <p>
        <asp:Button ID="btnEdit" runat="server" OnClick="btnEdit_Click" Text="Edit" />
&nbsp;<asp:Button OnClientClick ="return confirm('Do you wan't to Delete')" ID="btnDelete"  runat="server" OnClick="btnDelete_Click" Text="Delete" />
    </p>
    <p>
        &nbsp;</p>
</asp:Content>

public partial class EditDeleteGroups : System.Web.UI.Page
{
    ContactManagementEntities ctx = new ContactManagementEntities();
    protected void Page_Load(object sender, EventArgs e)
    {
        if(! IsPostBack )
        {
            ddlGroup.DataSource = ctx.ContactGroups.ToList();
            ddlGroup.DataTextField = "GroupName";
            ddlGroup.DataValueField = "GroupId";
            DataBind();
        }
    }
    protected void ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
    {
         var Grp = GetGroup();
        txtGroupName.Text = Grp.GroupName;
    }

    private ContactGroup GetGroup()
    {
        int intGroupId = Int32.Parse(ddlGroup.SelectedValue.ToString());
        var Grp = (from p in ctx.ContactGroups
                   where p.GroupId == intGroupId
                   select p).FirstOrDefault();
        return Grp;
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        try
        {

            var Grp = GetGroup();

            ctx.ContactGroups.Remove(Grp);
            ctx.SaveChanges();
            Response.Redirect("Default.aspx");
        }
        catch (DbUpdateException due)
        {
            lblMessage.Text = String.Format("There is records in the Contacts table which points to this '{0}'. First delete the the records in Contacts table refering to {0} and then delete the record.", txtGroupName.Text);
        }
        catch (Exception ex)
        {
            lblMessage.Text = "An error has occured";
        }
    }
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        var Grp = GetGroup();
        Grp.GroupName = txtGroupName.Text;
        ctx.SaveChanges();
        Response.Redirect("Default.aspx");
    }
}

Here I am writing a function called GetGroup which returns a single Contact Group based on the selection from Drop Down List.

On selecting an item from DropDownList I am filling the TextBox(es) with its corresponding data.

I  have also added exception handling to Delete so that Foreign key violation error is handled.


No comments:

Post a Comment