Visual C# Finish the code: private void btnAddContact_Click(object sender, Event
ID: 3602287 • Letter: V
Question
Visual C#
Finish the code:
private void btnAddContact_Click(object sender, EventArgs e)
{
string strContact;
//Validate data
//Assign strContact to Contact name(30 chars) + Contact Phone + Phone Source(7 chars)
//Add contact to list box control using the string variable strContact
//clear Add contact data (contact name, contact phone and phone source)
//set focus to contact name
private void btnOpen_Click(object sender, EventArgs e)
{
//define a StreamReader variable and name it inputFile
string strInput;
//try
//{
//Use the Show Open dialog to allow the user to select/open a Contact List disk file
//The filename that is selected should be assigned to the field strDiskFileName
//Open the disk file using the OpenText method
//clear list box of any items it may have
//Set up a while loop using the EndOfStream property
//Read disk record into strInput
//Add contact to list box control
//Close disk file
//}
//catch (Exception ex)
//{
// MessageBox.Show("Problems with disk file:" + Environment.NewLine + ex.Message, "Disk File", MessageBoxButtons.OK, MessageBoxIcon.Information);
//}
}
private void btnSave_Click(object sender, EventArgs e)
{
//Declare StreamWriter variable and name it outputFile
int intCount, intloop;
string strOutput;
//Make sure there is at least one contact to save
if (lstContactNumbers.Items.Count=0)
{
MessageBox.Show("There are no contacts to save.", "Contact List", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (strDiskFileName=="") //If this is blank then a file was not opened, therefore, it is a new file that is to be saved.
{
sadSave.Title = "Save Contact List";
// Display Save As Dialog using if statement. Uncomment the following code and finish it
//if (sadSave.ShowDialog() == DialogResult.OK)
//{
// //assign strDiskFileName to the FileName that was entered
//}
//else
//{
// return; //Saving a disk file was cancelled
//}
}
//Open the disk file to be written over, not appended using the variable outputFile
//Get the number of contacts in the list
intCount = lstContactNumbers.Items.Count;
for (intloop = 0; intloop <= intCount - 1; intloop++)
{
//assign SelectedIndex of ListBox control to intloop
//assign strOutput to Text property of ListBox control
//write out contact to disk file making sure a newline character is placed at the end of the record.
}
// close disk file
}
private void btnDeleteContact_Click(object sender, EventArgs e)
{
int intIndex;
//make sure a contact is selected, if a contact is not selected display an appropriate message
//using the MessageBox class and exit the method.
//get selected index of the contact that was chosen and assign it to intIndex
//remove contact from list box by calling the RemoveAt method passing in the selected index (intIndex)
//lstContactNumbers.Items.?;
}
Explanation / Answer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LinqToObjects
{
[Serializable]
public class Contact
{
private Guid mId;
private string mFirstName;
private string mMiddleName;
private string mLastName;
private string mStreet;
private string mCity;
private string mState;
private string mZip;
private string mEmail;
private string mHousePhone;
private string mWorkPhone;
private string mCellPhone;
private string mFax;
public Contact()
{
mId = Guid.NewGuid();
}
public Contact(Guid ID)
{
mId = ID;
}
public Guid ID
{
get
{
return mId;
}
}
public string FirstName
{
get
{
return mFirstName;
}
set
{
mFirstName = value;
}
}
public string MiddleName
{
get
{
return mMiddleName;
}
set
{
mMiddleName = value;
}
}
public string LastName
{
get
{
return mLastName;
}
set
{
mLastName = value;
}
}
public string Street
{
get
{
return mStreet;
}
set
{
mStreet = value;
}
}
public string City
{
get
{
return mCity;
}
set
{
mCity = value;
}
}
public string State
{
get
{
return mState;
}
set
{
mState = value;
}
}
public string ZipCode
{
get
{
return mZip;
}
set
{
mZip = value;
}
}
public string Email
{
get
{
return mEmail;
}
set
{
mEmail = value;
}
}
public string HousePhone
{
get
{
return mHousePhone;
}
set
{
mHousePhone = value;
}
}
public string WorkPhone
{
get
{
return mWorkPhone;
}
set
{
mWorkPhone = value;
}
}
public string CellPhone
{
get
{
return mCellPhone;
}
set
{
mCellPhone = value;
}
}
public string Fax
{
get
{
return mFax;
}
set
{
mFax = value;
}
}
}
}
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;
amespace LinqToObjects
{
public partial class frmContactBook : Form
{
List<Contact> contacts; // create a typed list of contacts
Contact currentContact; // create a single contact instance
int currentPosition; // used to hold current position
string currentFilePath; // file path to current contact file
bool dirtyForm; // keep track of dirty forms
public frmContactBook()
{
InitializeComponent();
// initialize a new set of contact data
// in case the user is starting a new
// file; replaces this if the user
// opens an existing file
contacts = new List<Contact>();
currentContact = new Contact();
contacts.Add(currentContact);
currentPosition = 0;
dirtyForm = false;
}
private void tsbExit_Click(object sender, EventArgs e)
{
exitToolStripMenuItem_Click(this, new EventArgs());
}
private void tsbSave_Click(object sender, EventArgs e)
{
saveStripMenuItem_Click(this, new EventArgs());
}
private void tsbRemoveRecord_Click(object sender, EventArgs e)
{
removeToolStripMenuItem_Click(this, new EventArgs());
}
private void tsbFindContact_Click(object sender, EventArgs e)
{
// return if the search term was not provided
if (String.IsNullOrEmpty(tspSearchTerm.Text))
{
MessageBox.Show("Enter a last name in the space proved.", "Missing
Search Term");
return;
}
try
{
// using linq to objects query to get first matching name
var foundGuy =
(from contact in contacts
where contact.LastName == tspSearchTerm.Text
select contact).FirstOrDefault<Contact>();
// set the current contact to the found contact
currentContact = foundGuy;
currentPosition = contacts.IndexOf(currentContact);
// update the display by loading the
// found contact
LoadCurrentContact();
// clear the search term textbox and return
tspSearchTerm.Text = string.Empty;
return;
}
catch
{
MessageBox.Show("No matches were found", "Search Complete");
}
}
private void tsbNavBack_Click(object sender, EventArgs e)
{
// capture form changes and plug them
// into the current contact before
// navigating off the contact
SaveCurrentContact();
// don't exceed the left limit
if (currentPosition != 0)
{
currentPosition--;
currentContact = contacts[currentPosition];
LoadCurrentContact();
}
}
private void tsbNavForward_Click(object sender, EventArgs e)
{
// capture form changes and plug them
// into the current contact before
// navigating off the contact
SaveCurrentContact();
// don't exceed the right limit
if (currentPosition < contacts.Count - 1)
{
currentPosition++;
currentContact = contacts[currentPosition];
LoadCurrentContact();
}
}
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveCurrentContact();
currentContact = new Contact();
contacts.Add(currentContact);
ClearScreen();
dirtyForm = true;
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
if (dirtyForm == true)
{
if (MessageBox.Show(this, "You have not saved the current contact
data; would you like to save before starting a new " +
"contact database?", "Save Current Data",
MessageBoxButtons.YesNo) ==
System.Windows.Forms.DialogResult.Yes)
{
saveAsMenuItem_Click(this, new EventArgs());
}
else
{
// discard and start new document
contacts = new List<Contact>();
ClearScreen();
}
}
else
{
// start new document
contacts = new List<Contact>();
ClearScreen();
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (dirtyForm == true)
{
if (MessageBox.Show(this, "You have not saved the current contact
data; would you like to save before opening a different " +
"contact database?", "Save Current Data",
MessageBoxButtons.YesNo) ==
System.Windows.Forms.DialogResult.Yes)
{
saveAsMenuItem_Click(this, new EventArgs());
}
else
{
Open();
}
}
else
{
Open();
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
if (dirtyForm == true)
{
if (MessageBox.Show(this, "You have not saved the current contact
data; would you like to save before exiting?", "Save Current
Data",
MessageBoxButtons.YesNo)==System.Windows.Forms.DialogResult.Yes)
{
tsbSave_Click(this, new EventArgs());
}
else
{
Application.Exit();
}
}
else
{
Application.Exit();
}
}
private void saveStripMenuItem_Click(object sender, EventArgs e)
{
SaveCurrentContact();
if (String.IsNullOrEmpty(currentFilePath))
{
SaveFileDialog SaveFileDialog1 = new SaveFileDialog();
try
{
SaveFileDialog1.Title = "Save CON Document";
SaveFileDialog1.Filter = "CON Documents (*.con)|*.con";
if (SaveFileDialog1.ShowDialog() ==
System.Windows.Forms.DialogResult.Cancel)
{
return;
}
}
catch
{
return;
}
currentFilePath = SaveFileDialog1.FileName;
if (String.IsNullOrEmpty(currentFilePath))
{
return;
}
}
// persist the contacts file to disk
Serializer.Serialize(currentFilePath, contacts);
// tell the user the file was saved
MessageBox.Show("File " + currentFilePath + " saved.", "File Saved.");
// everything is saved, set the dirtyform
// boolean to false
dirtyForm = false;
}
private void saveAsMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog SaveFileDialog1 = new SaveFileDialog();
try
{
SaveFileDialog1.Title = "Save CON Document";
SaveFileDialog1.Filter = "CON Documents (*.con)|*.con";
if (SaveFileDialog1.ShowDialog() ==
System.Windows.Forms.DialogResult.Cancel)
{
return;
}
}
catch
{
return;
}
currentFilePath = SaveFileDialog1.FileName;
if (String.IsNullOrEmpty(currentFilePath))
{
return;
}
// persist the contacts file to disk
Serializer.Serialize(currentFilePath, contacts);
// tell the user the file was saved
MessageBox.Show("File " + currentFilePath + " saved.", "File Saved.");
// everything is saved, set the dirtyform
// boolean to false
dirtyForm = false;
}
private void removeToolStripMenuItem_Click(object sender, EventArgs e)
{
// make sure there are records
if (contacts.Count == 0)
{
// remove the current record
contacts.Remove(currentContact);
// check to see if the current
// position is at the limit
// and move up or down
// as required
if (currentPosition == 0)
currentPosition++;
else
currentPosition--;
// reload the current contact
// from the new position
currentContact = contacts[currentPosition];
LoadCurrentContact();
// dirty the form since a
// record was removed
dirtyForm = true;
}
}
private void listAllContactsToolStripMenuItem_Click(object sender,
EventArgs e)
{
// use linq to objects to create a list of contacts
// ordered by the contact's last name, first name,
// and middle name
var orderedCons =
(from contact in contacts
orderby contact.LastName ascending,
contact.FirstName ascending,
contact.MiddleName ascending
select contact);
// create an instance of the full list form and pass it's
// constructor the list converted to a List<Contact>
frmFullList f = new frmFullList(orderedCons.ToList<Contact>());
f.Show();
}
private void ClearScreen()
{
txtFirstName.Text = string.Empty;
txtMiddleName.Text = string.Empty;
txtLastName.Text = string.Empty;
txtStreet.Text = string.Empty;
txtCity.Text = string.Empty;
txtState.Text = string.Empty;
txtZipCode.Text = string.Empty;
txtHousePhone.Text = string.Empty;
txtWorkPhone.Text = string.Empty;
txtCellPhone.Text = string.Empty;
txtFax.Text = string.Empty;
txtEmailAddress.Text = string.Empty;
}
private void LoadCurrentContact()
{
// update the form fields
txtFirstName.Text = currentContact.FirstName;
txtMiddleName.Text = currentContact.MiddleName;
txtLastName.Text = currentContact.LastName;
txtStreet.Text = currentContact.Street;
txtCity.Text = currentContact.City;
txtState.Text = currentContact.State;
txtZipCode.Text = currentContact.ZipCode;
txtHousePhone.Text = currentContact.HousePhone;
txtWorkPhone.Text = currentContact.WorkPhone;
txtCellPhone.Text = currentContact.CellPhone;
txtFax.Text = currentContact.Fax;
txtEmailAddress.Text = currentContact.Email;
// display the current user in the status bar
tslViewWho.Text = "Now Viewing " +
txtFirstName.Text + " " + txtLastName.Text;
}
private void SaveCurrentContact()
{
if (!String.IsNullOrEmpty(txtFirstName.Text) &&
(!String.IsNullOrEmpty(txtLastName.Text)))
{
try
{
// get all of the textbox values and
// plug them into the current contact object
currentContact.FirstName = txtFirstName.Text;
currentContact.MiddleName = txtMiddleName.Text;
currentContact.LastName = txtLastName.Text;
currentContact.Street = txtStreet.Text;
currentContact.City = txtCity.Text;
currentContact.State = txtState.Text;
currentContact.ZipCode = txtZipCode.Text;
currentContact.HousePhone = txtHousePhone.Text;
currentContact.WorkPhone = txtWorkPhone.Text;
currentContact.CellPhone = txtCellPhone.Text;
currentContact.Fax = txtFax.Text;
currentContact.Email = txtEmailAddress.Text;
// reorder the contacts by last, first, and
// middle name to keep everything in correct
// alphabetical order
var orderedContacts =
(from contact in contacts
orderby contact.LastName ascending,
contact.FirstName ascending,
contact.MiddleName ascending
select contact).ToList<Contact>();
// set the contacts list to the newly
// ordered list
contacts = orderedContacts;
// update the current position index value
currentPosition = contacts.IndexOf(currentContact);
// reload the current contact
LoadCurrentContact();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
}
public void Open()
{
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
OpenFileDialog1.Title = "Open con Document";
OpenFileDialog1.Filter = "CON Documents (*.con)|*.con";
if (OpenFileDialog1.ShowDialog() ==
System.Windows.Forms.DialogResult.Cancel)
{
return;
}
currentFilePath = OpenFileDialog1.FileName;
if (String.IsNullOrEmpty(currentFilePath))
{
return;
}
if (System.IO.File.Exists(currentFilePath) == false)
{
return;
}
// deserialize file content into contacts
// list to make it available to the application
contacts = Serializer.Deserialize(currentFilePath);
// alphabetize the contact list
// by last, first, and middle name and
// push the results into a List<T>
var orderedContacts =
(from contact in contacts
orderby contact.LastName ascending,
contact.FirstName ascending,
contact.MiddleName ascending
select contact).ToList<Contact>();
// set the contacts to the ordered
// version of the contact list
contacts = orderedContacts;
// Load contacts at position zero
// if contacts list is not empty
if (contacts != null)
{
currentContact = contacts.ElementAt<Contact>(0);
LoadCurrentContact();
dirtyForm = false;
}
}
#endregion
The final region in this form class is used to handle the listbox control events. These controls are used to provide a Rolodex sort of functionality to the application. The listbox controls are loaded into the left hand split panel’s panel. The top listbox control displays all of the letters in the alphabet whilst the lower listbox control is used to display all matching last names beginning with the letter selected in the upper listbox.
Hide Copy Code
#region Listbox Event Handlers
The first function handles the selected index changed event for the upper listbox containing all of the letters of the alphabet. When a new letter is selected, this method uses a simple LINQ to Objects query to find all contacts with last names beginning with the selected letter. The lower listbox is then cleared and then the matches are then formatted into a string showing the contact’s last name, first name, and middle name and each formatted string is then added to the lower listbox control.
Hide Shrink Copy Code
/// <span class="code-SummaryComment"><summary></span>
/// Display matching contacts whose last name begins
/// with the letter selected from the alphabet
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="sender"></param></span>
/// <span class="code-SummaryComment"><param name="e"></param></span>
private void lstAlphas_SelectedIndexChanged(object sender, EventArgs e)
{
string alpha = lstAlphas.SelectedItem.ToString();
if (contacts != null)
{
try
{
// use linq to objects query to find
// last names matching the selected
// letter of the alphabet
var alphaGroup =
from contact in contacts
where contact.LastName.ToUpper().StartsWith(alpha)
select contact;
// clear out any names from the
// existing list
lstNames.Items.Clear();
// add the short list of matching
// names to the list box
foreach (var con in alphaGroup)
lstNames.Items.Add(con.LastName + ", " +
con.FirstName + " " + con.MiddleName);
// if not matches were found, tell the user
// with a note in the box
if (alphaGroup.Count<Contact>() < 1)
{
lstNames.Items.Clear();
lstNames.Items.Add("No matches were found");
}
}
catch
{
lstNames.Items.Clear();
lstNames.Items.Add("No matches were found");
}
}
}
private void lstNames_SelectedIndexChanged(object sender, EventArgs e)
{
// if there were no matches found, return from this function
if (lstNames.SelectedItem.ToString().Trim() == "No matches were found")
return;
// variables to hold parts of the name as search terms
string first, middle, last;
// get the last name
string[] arr = lstNames.SelectedItem.ToString().Trim().Split(',');
last = arr[0].Trim();
// get the first name
string[] arr2 = arr[1].ToString().Trim().Split(' ');
first = arr2[0].Trim();
// get the middle name
middle = arr2[1].Trim();
// cannot complete the query without the three values
// so return if the information is missing
if (String.IsNullOrEmpty(last) ||
String.IsNullOrEmpty(first) ||
String.IsNullOrEmpty(middle))
{
MessageBox.Show("This query requires a first, middle, and a last
name.",
"Missing Name Values");
return;
}
try
{
// using linq to objects query to get a collection of matching names
// when all three names match
var foundGuy =
(from contact in contacts
where contact.FirstName.Equals(first) &&
contact.LastName.Equals(last) &&
contact.MiddleName.Equals(middle)
select contact).FirstOrDefault<Contact>();
// set the current contact to the first found
// contact
currentContact = foundGuy;
// update the index position used to maintain
// the current position within the list
currentPosition = contacts.IndexOf(currentContact);
// reload the current contact and return
LoadCurrentContact();
return;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Encountered");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.