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

We have shifted..

https://programmingpalace.wordpress.com/ is now http://thetechstory.com/

Find this Tutorial in the given link.

http://thetechstory.com/2012/09/27/net-project-demonstrating-mvc-pattern-using-c-contact-information-management-systemcims-part-7-viewing-all-contacts/

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

We have shifted..

https://programmingpalace.wordpress.com/ is now http://thetechstory.com/

Find this Tutorial in the given link.

http://thetechstory.com/2012/09/27/net-project-demonstrating-mvc-pattern-using-c-contact-information-management-systemcims-part-6-adding-a-new-contact/

.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

.NET Project Demonstrating MVC Pattern using C# – Contact Information Management System(CIMS)-Part 3 Search Functionality

Searching a Contact

After the successful Login, a Welcome Screen appears which looks like this.

WelcomeScreen

Here the User can search for a Contact Using either Contact Id or First Name.

If the Contact exists then it gets displayed on the Contact Group Box or else a Message Box pops up telling that the Contact doesn’t exist. The user can then Edit or Delete the selected contact.

The Code of WelcomeForm.cs is as 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 WelcomeForm : Form
    {
        public WelcomeForm()
        {
            InitializeComponent();
        }

        private void WelcomeForm_Load(object sender, EventArgs e)
        {
            textBoxContactId.Focus();

            //In case of Advanced Search when the Contact Id comes from the Advanced Search Form this is used
            if (textBoxContactId.Text !="")
            {
                showData();
            }

        }

        #region showData Method
        //showData method is used to fetch Contact Details using Contact Id
        private void showData()
        {
            //Exception is thrown when the user enters invalid Contact Id like Characters
            //So we are putting the code in try block
            try
            {
                Int32 iContactId = Convert.ToInt32(textBoxContactId.Text);

                ContactBO objContactBO = new ContactBO();

                objContactBO = ContactBL.GetContactDetails(iContactId);

                //Searching Using Contact Id
                //Checking if Contact Id exists
                if (objContactBO.ContactId != 0)
                {
                    //Making the labels controls Visible which will display the Search Result
                    labelContactIdResult.Visible = labelNameResult.Visible = true;
                    labelMobileNumResult.Visible = labelEmailIdResult.Visible = true;
                    labelDOBResult.Visible = true;

                    //Displaying the Search Result in Label Controls
                    labelContactIdResult.Text = objContactBO.ContactId.ToString();
                    string sFName = objContactBO.FirstName;
                    string sLName = objContactBO.LastName;
                    sFName = sFName.Trim();
                    sLName = sLName.Trim();
                    labelNameResult.Text = sFName + " " + sLName;
                    labelMobileNumResult.Text = objContactBO.MobileNumber;
                    labelEmailIdResult.Text = objContactBO.EmailId;
                    labelDOBResult.Text = objContactBO.DOB.ToShortDateString();

                    //Making the link Controls Visible giving the option to the User to either Edit or Delete a contact
                    linkLabelEdit.Visible = true;
                    linkLabelDelete.Visible = true;
                }

                else
                {
                    MessageBox.Show("Contact Id doesn't exist");
                    textBoxContactId.Focus();
                }
            }//try end

            //Here we are handling the exception
            catch (Exception ex)
            {
                MessageBox.Show("Invalid Contact Id");
            }

        }
        #endregion

        #region Searching a Contact
        //Code for Searching a Contact
        private void buttonSearch_Click(object sender, EventArgs e)
        {
            //Searching using Contact Id
            if (textBoxContactId.Text != "")
            {
                showData();

            }//Searching Using Contact Id ends

            //Searching Using First Name
            else if (textBoxFirstName.Text != "")
            {
                string sFName = textBoxFirstName.Text;

                List<ContactBO> lstContactDetails = new List<ContactBO>();
                lstContactDetails = ContactBL.GetContactDetails(sFName);

                //Checking if any Contact with the First Name Exists
                //The List will return zero if no contact is there with the First Name
                //Else Advanced Search Form will display with all the Contacts
                if (lstContactDetails.Count != 0)
                {
                    AdvancedSearchForm frmAS = new AdvancedSearchForm();
                    frmAS.textBoxFirstName.Text = sFName;
                    this.Hide();
                    frmAS.ShowDialog();
                }
                else
                {
                    MessageBox.Show("First Name doesn't exist");
                }

            }//Searching Using First Name ends
            else
            {
                MessageBox.Show("Enter a Contact Id or Name first");
            }

        }//Code For Search ends
        #endregion

        #region Edit Link Control
        //The Code for Edit Link Control
        private void linkLabelEdit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

            EditContact frmEditContact = new EditContact();
            frmEditContact.textBoxContactId.Text = labelContactIdResult.Text;
            frmEditContact.ShowDialog();

        }
        #endregion

        #region Delete Link Control
        //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");
                }
            }

        }

        #endregion

        #region Add New Contact Menu Item
        //Code for Add New Contact Menu Item
        private void contactToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddNewContact frmAddNew = new AddNewContact();
            frmAddNew.ShowDialog();
        }

        #endregion

        #region View All Contacts Menu Item
        //Code for View All Contacts Menu Item
        private void contactsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ViewAllContacts frmViewAll = new ViewAllContacts();
            frmViewAll.ShowDialog();
        }

        #endregion

        #region Logoff Menu Item
        //Code for Logoff Menu Item
        private void logoffToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            LoginForm frmLogin = new LoginForm();
            MessageBox.Show("You have Successfully Logged off");
            this.Hide();
            frmLogin.ShowDialog();
        }
        #endregion

    }
}

The welcome Form calls the following methods in ContactBL class.

public static ContactBO GetContactDetails(Int32 iContactId)
public static List<ContactBO> GetContactDetails(string sFName)

We have seen their code in the previous tutorial.

We can have two contacts with the same First Name, so when the user search using the First Name then another form called Advanced Search Form displays, it shows all the existing contacts with the same First Name in the DataGridView Control.

The Advanced Search Form is below

AdvancedSearchFormDesign

 

The code for AdvancedSearchForm.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 AdvancedSearchForm : Form
    {
        public AdvancedSearchForm()
        {
            InitializeComponent();
        }

        //The Contacts with same First Name are loaded in the DataGridView Control
        private void AdvancedSearchForm_Load(object sender, EventArgs e)
        {
            string sFName = textBoxFirstName.Text;
            List<ContactBO> lstContactDetails = new List<ContactBO>();

            lstContactDetails = ContactBL.GetContactDetails(sFName);

            dataGridViewContactDetails.DataSource = lstContactDetails;

        }

        //Make the DataGridView Control Read Only so that the user can't edit the values.
        //When the user clicks on a Particular Contact here then Welcome Form displays with the Contact Details
        private void dataGridViewContactDetails_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string sContactId = dataGridViewContactDetails.SelectedCells[0].Value.ToString();
            WelcomeForm frmWF = new WelcomeForm();
            frmWF.textBoxContactId.Text = sContactId;
            this.Hide();
            frmWF.ShowDialog();
        }

    }
}

Running the Project

After successful login, the Welcome Screen displays. Enter a Contact Id to search a contact. The Contact Details display in the Group Box below.

SearchContactUsingContactId

If the user tries to search using a Contact Id which doesn’t exist, a Message Box pops up telling that the Contact Id doesn’t exist.

SearchingUsingInvalidContactIdDisplaysErrorMessage

The user search can also search using First Name

SearchingUsingFirstName

If the Contact with First Name exists then Advanced Search Form displays with all the Contacts of same First Name.

AdvancedSearchForm displays with all the Contacts of same First Name

When the user click on a Contact in DataGridView Control, then the Welcome Form gets displayed with the Contact Details displayed in the Contact Group Box.

AdvancedSearch3

If the user tries to search a Contact with a FirstName which doesn’t exist then an Error Message displays.

SearchingAContactUsingFirstName_which_doesnt_exist