Connecting Multiple Databases in .NET using C# – Part 2 Building the UI and Final Application

This is part 2 of the Tutorial Series Connecting Multiple Databases in .NET using C#. We will see the UI and the final application in this part.

UI

Make a Select DB Form, Search Contact Form and Advance Search Form. Add reference of BL and BO here.

Snapshots of the UI is as below

SelectDBForm

SearchContactForm

AdvanceSearchForm

The code behind this files.

SelectDatabaseForm.cs

namespace UI
{
    public partial class SelectDatabaseForm : Form
    {
        public SelectDatabaseForm()
        {
            InitializeComponent();
            comboBoxSelectDB.SelectedIndex = 0;
        }

        //string sDatabase will store the selected Database of the user
        public static string sDatabase = string.Empty;

        private void buttonGo_Click(object sender, EventArgs e)
        {
            if (comboBoxSelectDB.Text == string.Empty)
            {
                MessageBox.Show("Select a Database to connect first");
            }
            else
            {
                sDatabase = comboBoxSelectDB.Text;
                SearchContactForm frmSearch = new SearchContactForm();
                this.Hide();
                frmSearch.ShowDialog();
            }
       }//Button Go Click event end here.
    }
}

SearchContactForm.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 BO;
using BL;

namespace UI
{
    public partial class SearchContactForm : Form
    {
        public SearchContactForm()
        {
            InitializeComponent();
            textBoxContactId.Focus();
        }

        //Fetching the Selected Database Name from the SelectConnection Form
        private string sDatabase = SelectDatabaseForm.sDatabase;

        private void SearchContactForm_Load(object sender, EventArgs e)
        {
            //In case of Advanced Search when the Contact Id comes from the Advanced Search Form this is used
            if (textBoxContactId.Text != "")
            {
                showData();
            }

            labelDBName.Text = sDatabase;
            this.Text = "Search Contact Form || Selected Database - "+sDatabase;
        }

        #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(sDatabase, 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();

                }

                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");
                MessageBox.Show(ex.ToString());
            }

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

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

                List lstContactDetails = new List();
                lstContactDetails = ContactBL.GetContactDetails(sDatabase, 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 to search");
            }
        }

        //Code for LinkLabel Control Change Database
        private void linkLabelChangeDB_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectDatabaseForm frmSC = new SelectDatabaseForm();
            this.Hide();
            frmSC.ShowDialog();
        }

    }
}

AdvancedSearchForm.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 BO;
using BL;

namespace UI
{
    public partial class AdvancedSearchForm : Form
    {
        public AdvancedSearchForm()
        {
            InitializeComponent();
        }

        //Fetching the Selected Database Name from the SelectConnection Form
        private string sDatabase = SelectDatabaseForm.sDatabase;

        private void AdvancedSearchForm_Load(object sender, EventArgs e)
        {
            string sFName = textBoxFirstName.Text;
            List lstContactDetails = new List();

            lstContactDetails = ContactBL.GetContactDetails(sDatabase, 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 Search Contact Form displays with the Contact Details
        private void dataGridViewContactDetails_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string sContactId = dataGridViewContactDetails.SelectedCells[0].Value.ToString();
            SearchContactForm frmSF = new SearchContactForm();
            frmSF.textBoxContactId.Text = sContactId;
            this.Hide();
            frmSF.ShowDialog();
        }
    }
}

Screenshots of Running the Application

User needs to select the Database when the application starts. Here the user selects the Sql Server DB.

SelectDBForm_Running

Search Contact Form Displays when the user clicks on the Go Button. Here the user can search a Contact using either Contact Id or First Name. In this form we are also displaying the Selected DB name and we are also giving an option to the user to change the DB at runtime.

SearchFormOpens_with_DBSqlServer

Searching Using First Name

Searching_using_FirstName

Advanced Search Form displays showing all the contacts with the same First Name. Here in this Form also, we need to access the Database Name we selected previously.

AdvancedSearchFormOpens

When the user clicks on a contact in DataGridView Control, then it details get displayed in Search Contact Form.

AdvancedSearchDisplaysinSearchForm

When the user clicks on Change Database Link, then Select DB Form appears. Now the user can select another DB. This time the user select Oracle.

ChangingDatabaseAtRunTime

Searching Contact Using Oracle DB.

SearchContact_using_OracleDB

Done for the Day. Happy Programming. 😀

Connecting Multiple Databases in .NET using C# – Part 1 Introduction

We have shifted..

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

Find this Tutorial in the given link.

http://thetechstory.com/2012/09/29/connecting-multiple-databases-in-net-using-c-part-1-introduction/

.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