.NET Project Demonstrating MVC Pattern using C# – Contact Information Management System(CIMS)-Part 7 Viewing All Contacts

Viewing all Contacts

When the user clicks on File->View All->Contacts, then we are opening another Form called ViewAllContacts.cs.

This form contains a DataGridView Control which will display all the contacts of the user.

The DataGridView control gets populated when the Form gets loaded and displays all the existing contacts of the user.

When the user clicks on a Contact in DataGridView Control, it gets selected and displayed in the group box below. Make the DataGridView control read only so that user can’t change any data there and change the SelectionMode property to FullRowSelect

ViewAllContacts

Here’s the code for ViewAllContacts.cs.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CIMS.BO;
using CIMS.BL;

namespace CIMS.UI
{
    public partial class ViewAllContacts : Form
    {
        public ViewAllContacts()
        {
            InitializeComponent();
        }

        private void ViewAllContacts_Load(object sender, EventArgs e)
        {
            List<ContactBO> lstContactDetails = new List<ContactBO>();

            lstContactDetails = ContactBL.GetAllContactDetails();

            dataGridViewContactDetails.DataSource = lstContactDetails;
        }

        private void dataGridViewContactDetails_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Making the labels controls Visible which will display the Search Result
            labelContactIdResult.Visible = labelNameResult.Visible = true;
            labelMobileNumResult.Visible = labelEmailIdResult.Visible = true;
            labelDOBResult.Visible = true;

            labelContactIdResult.Text = dataGridViewContactDetails.SelectedCells[0].Value.ToString();

            string sFName = dataGridViewContactDetails.SelectedCells[1].Value.ToString();
            string sLName = dataGridViewContactDetails.SelectedCells[2].Value.ToString();

            sFName = sFName.Trim();
            sLName = sLName.Trim();
            labelNameResult.Text = sFName + " " + sLName;

            labelMobileNumResult.Text = dataGridViewContactDetails.SelectedCells[3].Value.ToString();
            labelEmailIdResult.Text = dataGridViewContactDetails.SelectedCells[4].Value.ToString();
            labelDOBResult.Text = dataGridViewContactDetails.SelectedCells[5].Value.ToString();

            linkLabelEdit.Visible = true;
            linkLabelDelete.Visible = true;

        }

        private void linkLabelEdit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            EditContact frmEditContact = new EditContact();
            frmEditContact.textBoxContactId.Text = labelContactIdResult.Text;
            frmEditContact.ShowDialog();
        }

        private void linkLabelDelete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Int32 iContactId = Convert.ToInt32(labelContactIdResult.Text);

            DialogResult result1 = MessageBox.Show("Are you sure you want to delete this Contact?",
                                  "Delete the Contact",
                                   MessageBoxButtons.YesNo);

            if (result1 == DialogResult.Yes)
            {
                int result = ContactBL.RemoveContact(iContactId);

                if (result > 0)
                {
                    MessageBox.Show("Contact Removed Successfully");
                }
            }
        }

    }
}

Here’s the GetAllContactDetails method in ContactBL.


 #region GetAllContactDetails Method
        public static List<ContactBO> GetAllContactDetails()
        {
            List<ContactBO> lstContactDetails = new List<ContactBO>();
            lstContactDetails = ContactDL.FetchAllContactDetails();
            return lstContactDetails;
        }
        #endregion

This method called a method in ContactDL called FetchAllContactDetails. This method connects to the Database and returns a list which contain the ContactBO objects.


  #region FetchAllContactDetails Method
        public static List<ContactBO> FetchAllContactDetails()
        {
            List<ContactBO> lstContactDetails = new List<ContactBO>();

            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("SELECT * FROM contact_details", conn);

                SqlDataReader rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                    lstContactDetails.Add(
                          new ContactBO()
                          {
                              ContactId = Convert.ToInt32(rdr["ContactId"].ToString()),
                              FirstName = rdr["FirstName"].ToString(),
                              LastName = rdr["LastName"].ToString(),
                              MobileNumber = rdr["MobileNumber"].ToString(),
                              EmailId = rdr["EmailId"].ToString(),
                              DOB = Convert.ToDateTime(rdr["DOB"].ToString())

                          }
                      );

                }
                rdr.Close();
                conn.Close();

                return lstContactDetails;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        #endregion

Snapshots of Viewing all Contacts

User select File->View All->Contacts

1GoToViewAllMenuItem

A new Form opens called ViewAllContacts appears.  The DataGridView control gets populated when the Form gets loaded and displays all the existing contacts of the user.

When the user clicks on a Contact in DataGridView Control, it gets selected and displayed in the group box below.

2ViewAllContactsFormOpen

And with that we come to the end of Insert, Update Delete Procedure using MVC architecture in .NET in C# Programming Language.

Hope you now have the basic understanding of how to work with MVC Pattern. :D

.NET Project Demonstrating MVC Pattern using C# – Contact Information Management System(CIMS)-Part 6-Adding a New Contact

Adding a New Contact

When the user select File->New->Contact, a new Form opens called AddNewContact.cs. Here the user need to add details of the new contact and clicks on the Save Button. A message box pops up giving a confirmation message that the new contact get successfully added.

Snapshot of AddNewContact Form  called AddNewContact.cs. Name the text boxes appropriately. We named as textboxFName,   textboxLName,  textboxMobile etc.

AddNewContact Form

Here’s the code for AddNewContact.cs. It does some validation checking that the fields are not empty, then it creates a ContactBO object of the data submitted by the user. The ContactBO is passes as a parameter to  AddNewContactDetails method in ContactBL.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CIMS.BO;
using CIMS.BL;

namespace CIMS.UI
{
    public partial class AddNewContact : Form
    {
        public AddNewContact()
        {
            InitializeComponent();
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            if(textBoxFName.Text=="")
            {
                MessageBox.Show("First Name can't be empty");
            }
            else if(textBoxLName.Text =="")
            {
                MessageBox.Show("Last Name can't be empty");
            }

            else if (textBoxMobile.Text == "")
            {
                MessageBox.Show("Mobile Number can't be empty");
            }
            else if (textBoxEmail.Text == "")
            {
                MessageBox.Show("Email Id can't be empty");
            }

            else
            {
                ContactBO objContactBO = new ContactBO();

                objContactBO.FirstName = textBoxFName.Text;
                objContactBO.LastName = textBoxLName.Text;
                objContactBO.MobileNumber = textBoxMobile.Text;
                objContactBO.EmailId = textBoxEmail.Text;
                objContactBO.DOB = dateTimePickerDOB.Value;

                int result = ContactBL.AddNewContactDetails(objContactBO);

                if (result > 0)
                {
                    MessageBox.Show("Contact Added Successfully");
                    this.Hide();
                    //WelcomeForm frm = new WelcomeForm();
                    //frm.ShowDialog();
                }
                else
                {
                    MessageBox.Show("Can't add New Contact");
                }

            }//else end
        }

    }
}

Here’s the AddNewContactDetails method in ContactBL.


 public static int AddNewContactDetails(ContactBO objContactBO)
        {
            ContactDL objContactDL = new ContactDL();
            int result = objContactDL.AddNewContactDetails(objContactBO);
            return result;
        }

This method called a method in ContactDL called AddNewContactDetails. This method connects to the Database and insert the new Contact in the Database.


 public static int AddNewContactDetails(ContactBO objContactBO)
        {

            try
            {
                Int32 iContactId = objContactBO.ContactId;
                string sFName = objContactBO.FirstName;
                string sLName = objContactBO.LastName;
                string sMobileNumber = objContactBO.MobileNumber;
                string sEmailId = objContactBO.EmailId;
                DateTime dtDOB = objContactBO.DOB;

                conn.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO contact_details(FirstName, LastName, MobileNumber, EmailId, DOB)"
                + "VALUES (@FName, @LName, @MobileNumber, @EmailId, @DOB)", conn);

                cmd.Parameters.Add(new SqlParameter("@FName", sFName));
                cmd.Parameters.Add(new SqlParameter("@LName", sLName));
                cmd.Parameters.Add(new SqlParameter("@MobileNumber", sMobileNumber));
                cmd.Parameters.Add(new SqlParameter("@EmailId", sEmailId));
                cmd.Parameters.Add(new SqlParameter("@DOB", dtDOB));

                int result = cmd.ExecuteNonQuery();

                conn.Close();

                return result;
            }
            catch (Exception e)
            {
                throw e;
            }

        }

Snapshots of Adding a New Contact

User select File->New->Contact

A new Form opens called AddNewContact appears. The user can add details of a Contact here.

AddingNewContactDetails

When the user clicks on the Save Button, a message box pops up telling that contact successfully added.

ContactGetSuccessfullyAdded

.NET Project Demonstrating MVC Pattern using C# – Contact Information Management System(CIMS)-Part 5-Deleting a Contact

Deleting a Contact

When the User clicks on Delete LinkLabel Control in the WelcomeForm or AdvanceSearch Form, a Message Box pops us asking the user whether he really wants to delete the contact. Based on the user selection the contact gets removed.

The Code in WelcomeForm.cs for Delete Link Label Control click event is below


   //Code for Delete Link Control
        private void linkLabelDelete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Int32 iContactId = Convert.ToInt32(labelContactIdResult.Text);

             DialogResult result1= MessageBox.Show("Are you sure you want to delete this Contact?",
                                   "Delete the Contact",
                                    MessageBoxButtons.YesNo);

             if (result1 == DialogResult.Yes)
             {
                 int result = ContactBL.RemoveContact(iContactId);

                 if (result > 0)
                 {
                     MessageBox.Show("Contact Removed Successfully");
                 }
             }

        }

In the WelcomeForm.cs, in the Delete Link click event, we are opening a Message Box with Yes, No Buttons. If the user select Yes then we are calling a Method called RemoveContact  in ContactBL taking the Contact Id of the User as an Input Parameter.


  public static int RemoveContact(Int32 iContactId)
        {
            int result = ContactDL.DeleteContactDetails(iContactId);
            return result;
        }

This method calls a method in ContactDL called  DeleteContactDetails

 public static int DeleteContactDetails(Int32 iContactId)
        {
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("DELETE FROM contact_details WHERE ContactId = @Id", conn);

                cmd.Parameters.Add(new SqlParameter("@Id", iContactId));

                int result = cmd.ExecuteNonQuery();

                conn.Close();
                return result;

            }
            catch (Exception e)
            {
                throw e;
            }

        }

This method deletes the Contact from the Database table.

Snapshots of Removing a Contact.

Select a contact for Deleting and click on the Delete link. 

SelectContactForDeleting

A message box appears asking whether you want to delete or not.

UserCanSelectWhetherToDeleteOrNot

When the user select Yes the Contact get removed and a message box pops us giving a Confirmation Message.

IfUserSelectsYesThenContactGetParmanentlyRemoved

.NET Project Demonstrating MVC Pattern using C# – Contact Information Management System(CIMS)-Part 4-Editing a Contact

Editing a Contact

When the User clicks on Edit LinkLabel Control in the WelcomeForm or AdvanceSearch Form, we open another Form called EditContact.cs. This Form gets populated with the data of an existing selected contact. The user can edit it from there.

Snapshot of Edit Contact Form EditContact.cs.

EditContactForm

The code for EditContact.cs is below.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CIMS.BO;
using CIMS.BL;

namespace CIMS.UI
{
    public partial class EditContact : Form
    {
        public EditContact()
        {
            InitializeComponent();
        }

        //Fetching an Existing Contact Details in Text Boxes
        private void EditContact_Load(object sender, EventArgs e)
        {
            Int32 iContactId = Convert.ToInt32(textBoxContactId.Text);
            ContactBO objContactBO = new ContactBO();

            objContactBO = ContactBL.GetContactDetails(iContactId);

            textBoxFName.Text = objContactBO.FirstName;
            textBoxLName.Text = objContactBO.LastName;
            textBoxMobile.Text = objContactBO.MobileNumber;
            textBoxEmail.Text = objContactBO.EmailId;
            dateTimePickerDOB.Value = objContactBO.DOB;
        }

        //Updating the Contact in DB
        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            ContactBO objContactBO = new ContactBO();

            objContactBO.ContactId = Convert.ToInt32(textBoxContactId.Text);
            objContactBO.FirstName = textBoxFName.Text;
            objContactBO.LastName = textBoxLName.Text;
            objContactBO.MobileNumber = textBoxMobile.Text;
            objContactBO.EmailId = textBoxEmail.Text;
            objContactBO.DOB = dateTimePickerDOB.Value;

            int result= ContactBL.UpdateContactDetails(objContactBO);

            if (result > 0)
            {
                MessageBox.Show("Contact Updated Successfully");
                this.Hide();

            }
            else
                MessageBox.Show("Failed to update Contact");

        }
    }
}

Here on the Update Button Click Event, we are calling a method in ContactBL that takes a ContactBO Business Object.

 public static int UpdateContactDetails(ContactBO objContactBO)
        {
            int result = ContactDL.UpdateContactDetails(objContactBO);
            return result;
        }

This method calls another method in ContactDL called UpdateContactDetails
This method takes a ContactBO Business Object, fetch all data from it and update it in the Database.


 public static int UpdateContactDetails(ContactBO objContactBO)
        {

            try
            {
                Int32 iContactId = objContactBO.ContactId;
                string sFName = objContactBO.FirstName;
                string sLName = objContactBO.LastName;
                string sMobileNumber = objContactBO.MobileNumber;
                string sEmailId = objContactBO.EmailId;
                DateTime dtDOB = objContactBO.DOB;

                conn.Open();
                SqlCommand cmd = new SqlCommand("UPDATE contact_details SET FirstName = @FName, LastName = @LName,"+
                    "MobileNumber = @MobileNumber , EmailId = @EmailId, DOB = @DOB WHERE ContactId = @Id", conn);

                cmd.Parameters.Add(new SqlParameter("@Id", iContactId));
                cmd.Parameters.Add(new SqlParameter("@FName", sFName));
                cmd.Parameters.Add(new SqlParameter("@LName", sLName));
                cmd.Parameters.Add(new SqlParameter("@MobileNumber", sMobileNumber));
                cmd.Parameters.Add(new SqlParameter("@EmailId", sEmailId));
                cmd.Parameters.Add(new SqlParameter("@DOB", dtDOB));

                int result = cmd.ExecuteNonQuery();

                conn.Close();

                return result;

            }
            catch (Exception e)
            {
                throw e;
            }

        }

Snapshots of Editing a Contact

Select a Contact for Editing by clicking on the Edit Link below a Contact
SelectContactForEditing

Another Window will open with text boxes to edit that contact

EditFormOpens

Update the Contact Details

When the user clicks on the Update button the Contact gets updated.

ContactGetUpdated