Home

The Combo Box: Creating and Selecting Items

 
 

Introduction

Like all visual controls, a combo box shares all the basic characteristics of other graphic control: the name, the location, the size, the ability to be enabled or disabled, the ability to hide or show it, the ability to dock or anchor, etc.

 

Creating the List of Items

Probably the most important aspect of a combo box is the list of items it holds. Like the list box and all other list-based controls, the list of a combo box is held by the Items property. You create this list using the exact same techniques we reviewed for the list box. This means that you can use the String Collection Editor.

The Items property of the ComboBox class is created from the nested ObjectCollection class. This class has the same functionality and features as its counterpart of the list box. This means that, to programmatically create of items, you can (continuously) call the ObjectCollection.Add() method. Here is an example:

public class Exercise : System.Windows.Forms.Form
{
    Label lblTitle;
    ComboBox cbxAcademicDisciplines;

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        lblTitle = new Label();
        lblTitle.Text = "Academic Disciplines";
        lblTitle.Location = new Point(12, 12);
        lblTitle.AutoSize = true;
        Controls.Add(lblTitle);

        cbxAcademicDisciplines = new ComboBox();
        cbxAcademicDisciplines.Location = new Point(12, 32);
        cbxAcademicDisciplines.Items.Add("Natural sciences");
        cbxAcademicDisciplines.Items.Add("Mathematics and Computer sciences");
        cbxAcademicDisciplines.Items.Add("Social sciences");
        cbxAcademicDisciplines.Items.Add("Humanities");
        cbxAcademicDisciplines.Items.Add("Professions and Applied sciences");

        Controls.Add(cbxAcademicDisciplines);
    }
}

This would produce:

Combo Box

To add an array of items, you can call the AddRange() method. To insert an item somewhere inside the list, you can call the Insert() method.

If you want the list of items to be sorted, you can change the value of the Sorted property in the Properties window from False (the default) to True. To sort a list programmatically, you can assign a true value to the Sorted property. You can un-sort the list by changing the value of the Sorted property. This property works exactly like its equivalent in the ListBox control.

Practical Learning Practical Learning: Using the ObjectCollection Class

  1. To create a list of items using the Add() method, double-click an unoccupied area of the form and implement its Load event as follows:
     
    private void Central_Load(object sender, EventArgs e)
    {
            for (int i = DateTime.Now.Year; i >= 1960; i--)
                    this.cbxCarYears.Items.Add(i);
    }
  2. Save the form

Selecting an Item

To select an item from the list, the user can click it. To programmatically select an item, you can assign a string to the Text property of a DropDown or a Simple combo box. Probably the best way to select an item is to specify its index. The items of a combo box are stored in a zero-based list. To select an item, you can assign its position to the SelectedIndex property. In the same way, to find out what item is selected, you can get the value of the SelectedIndex property.

Instead of using of using the index of an item, to select an item using its identity or name, you can use the SelectedItem property. To select an item by its name, assign it to the SelectedItem property.

Practical Learning Practical Learning: Using the ObjectCollection Class

  1. On the main menu, click Project -> Add Class...
  2. Set the name to PartDescription and press Enter
  3. To create a class that can holds a structured item of a list, change the class as follows:
     
    using System;
    
    namespace CollegeParkAutoParts1
    {
        public class PartDescription
        {
            private long ID;
            private int yr;
            private string mk;
            private string mdl;
            private string cat;
            private string name;
            private decimal price;
    
            public PartDescription()
            {
                this.ID = 0;
                this.yr = 1960;
                this.mk = "";
                this.mdl = "";
                this.name = "Unknown";
                this.price = 0.00M;
            }
    
            public PartDescription(long code, int year, string make,
                                   string model, string type,
                                   string desc, decimal UPrice)
            {
                this.ID = code ;
                this.yr = year;
                this.mk = make;
                this.mdl = model;
                this.cat = type;
                this.name = desc;
                this.price = UPrice;
            }
    
            public long PartNumber
            {
                get { return ID; }
                set { ID = value; }
            }
    
            public int CarYear
            {
                get { return yr; }
                set { yr = value; }
            }
    
            public string Make
            {
                get { return mk; }
                set { mk = value; }
            }
    
            public string Model
            {
                get { return mdl; }
                set { mdl = value; }
            }
    
            public string Category
            {
                get { return cat ; }
                set { cat = value; }
            }
    
            public string PartName
            {
                get { return name; }
                set { name = value; }
            }
    
            public decimal UnitPrice
            {
                get { return (price < 0) ? 0.00M : price; }
                set { price = value; }
            }
    
            public override string ToString()
            {
                return this.PartNumber + " " +
                       this.CarYear.ToString() + " " +
                       this.Make + " " +
                       this.Model + " " +
                       this.Category + " " +
                       this.PartName + " " +
                       this.UnitPrice;
            }
        }
    }
  4. Access the Central.cs code file and change it as follows:
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    
    namespace CollegeParkAutoParts1
    {
        public partial class Central : Form
        {
            PartDescription[] parts = new PartDescription[56];
    
            public Central()
            {
                InitializeComponent();
            }
    
            private void Central_Load(object sender, EventArgs e)
            {
                for (int i = DateTime.Now.Year; i >= 1960; i--)
                    this.cbxCarYears.Items.Add(i);
    
                parts[0] = new PartDescription(447093, 2002, "Ford",
                    "Escort SE L4 2.0", "Engine Electrical",
                    "Alternator 75amp  Remanufactured; w/ 75 Amp",
                    205.05M);
                parts[1] = new PartDescription(203815, 2006, "Dodge",
                    "Caravan SE L4 2.4", "Cooling System",
                    "Radiator Cap", 6.65M);
                parts[2] = new PartDescription(293047, 2000, "Toyota",
                    "RAV4 2WD/4-DOOR", "Cooling System",
                    "Thermostat Gasket", 4.95M);
                parts[3] = new PartDescription(990468, 2002, "Honda",
                    "Civic 1.7 EX 4DR", "Exhaust",
                    "Bolt & Spring Kit (Manifold outlet, Muffler Inlet)",
                    85.75M);
                parts[4] = new PartDescription(304158, 1996, "Buick",
                    "Regal Custom V6 3.8", "Fuel Injection",
                    "Fuel Injector", 82.75M);
                parts[5] = new PartDescription(807245, 2004, "Acura",
                    "MDX 3.5 4WD", "Driveshaft & Axle",
                    "CV Boot Clamp 7 x 750mm; 1 Large + 1 Small Clamp",
                    1.60M);
                parts[6] = new PartDescription(203485, 2001, "Ford",
                    "Taurus LX V6 3.0", "Fuel Injection",
                    "Oxygen Sensor OE Style 4Wire; Front; 2 Required",
                    52.65M);
                parts[7] = new PartDescription(248759, 1999, "Jeep",
                    "Wrangler Sahara", "Air Intake",
                    "Air Filter AirSoft Panel", 7.95M);
                parts[8] = new PartDescription(202848, 1998, "Honda",
                    "Accord 2.3 LX 4DR", "Air Intake",
                    "Air Filter", 12.55M);
                parts[10] = new PartDescription(932759, 2006, "Kia",
                    "Rio 1.6DOHC16V 4-DR", "Cooling System",
                    "Thermostat", 14.45M);
                parts[11] = new PartDescription(304975, 2000, "Honda",
                    "Civic 1.6 EX 4DR", "Suspension",
                    "Ball Joint; Front Lower; 2 per car", 40.55M);
                parts[12] = new PartDescription(208450, 2003, "Chevrolet",
                    "Monte Carlo LS V6 3.4", "Fuel Injection",
                    "Oxygen Sensor OE connector; Rear", 65.55M);
                parts[13] = new PartDescription(209480, 2002, "Ford",
                    "Focus SE DOHC L4 2.0", "Steering",
                    "Steering Rack Remanufactured", 170.85M);
                parts[9] = new PartDescription(203495, 2004, "Honda",
                    "Civic 1.7 EX 4DR", "Climate Control",
                    "A/C Clutch; OE compressor = Sanden", 184.95M);
                parts[14] = new PartDescription(203480, 2007, "Toyota",
                    "Corolla", "Air Intake",
                    "Air Filter", 12.65M);
                parts[15] = new PartDescription(109379, 2005, "Volvo",
                    "S40 2.5L T5 AWD", "Fuel Delivery",
                    "Fuel Filter; Early Design; Outer Diameter = 55mm",
                    30.95M);
                parts[16] = new PartDescription(935794, 2002, "Ford",
                    "Escape XLS 4WD", "Brake",
                    "Brake Caliper Remanufactured; Front Right",
                    65.55M);
                parts[17] = new PartDescription(203485, 2006, "BMW",
                    "325i", "Climate Control",
                    "AC High Pressure Side Switch",
                    49.95M);
                parts[18] = new PartDescription(204875, 1996, "Chevrolet",
                    "Monte Carlo Z34 V6 3.4", "Fuel Delivery",
                    "Fuel Filter", 8.05M);
                parts[19] = new PartDescription(937485, 2007, "Toyota",
                    "Camry V6", "Air Intake", "Air Filter", 12.95M);
                parts[20] = new PartDescription(294759, 2001, "Ford",
                    "Escape XLT 4WD", "Air Intake",
                    "Air Filter Panel", 7.25M);
                parts[21] = new PartDescription(297495, 2003, "Honda",
                    "Civic 1.7 EX 4DR", "Brake",
                    "Brake Caliper Reman; w/ ProAct Pads; Front Right",
                    82.55M);
                parts[22] = new PartDescription(794735, 2006, "BMW",
                    "325i", "Climate Control",
                    "Cabin Air/Pollen Filter; With Activated Carbon",
                    28.05M);
                parts[23] = new PartDescription(937485, 2007, "Toyota",
                    "Corolla", "Body Electrical",
                    "Halogen  SilverStar; 12V 65W; inner-high beam",
                    22.85M);
                parts[24] = new PartDescription(492745, 2005, "Ford",
                    "Focus ZX3 L4 2.0", "Air Intake",
                    "Fuel Injection Perf Kit", 342.95M);
                parts[25] = new PartDescription(937005, 2004, "Acura",
                    "MDX 3.5 4WD", "Driveshaft & Axle",
                    "CV Boot Clamp 7 x 750mm; For Large End of Boot; inner boot",
                    1.60M);
                parts[26] = new PartDescription(293749, 2004, "Acura",
                    "MDX 3.5 4WD", "Driveshaft & Axle",
                    "Axle Nut 24mm x 1;5; rear ",
                    2.35M);
                parts[27] = new PartDescription(920495, 2006, "BMW",
                    "325i", "Climate Control",
                    "Adjustable Telescoping Mirror", 7.95M);
                parts[28] = new PartDescription(204075, 2004, "Acura",
                    "MDX 3.5 4WD", "Driveshaft & Axle",
                    "Wheel Bearing; Rear; 1 per wheel",
                    70.15M);
                parts[29] = new PartDescription(979304, 2000, "Toyota",
                    "RAV4 2WD/4-DOOR", "Cooling System",
                    "Thermostat Housing", 20.95M);
                parts[30] = new PartDescription(300456, 2004, "Acura",
                    "MDX 3.5 4WD", "Driveshaft & Axle",
                    "Wheel Bearing; Front; 1 per wheel",
                    66.65M);
                parts[31] = new PartDescription(404860, 2001, "Ford",
                    "Taurus LX V6 3.0", "Suspension",
                    "Shock Absorber GR2; Rear; Wagon only",
                    39.40M);
                parts[32] = new PartDescription(585688, 2007, "Buick",
                    "Lacrosse CXS V6 3.6", "Brake",
                    "Climate Control", 10.65M);
                parts[33] = new PartDescription(739759, 2001, "Ford",
                    "Taurus LX V6 3.0", "Suspension",
                    "Shock Absorber GasaJust; Rear; Wagon only",
                    30.95M);
                parts[34] = new PartDescription(927495, 2005, "Volvo",
                    "S40 2.5L T5 AWD", "Engine Mechanical",
                    "Timing Belt Idler Pulley Original Equipment INA",
                    65.55M);
                parts[40] = new PartDescription(979374, 2000, "Toyota",
                    "RAV4 2WD/4-DOOR", "Cooling System",
                    "Thermostat Gasket", 4.95M);
                parts[35] = new PartDescription(542347, 2007, "Buick",
                    "Lacrosse CXS V6 3.6", "Brake",
                    "Brake Pad Set ProACT Ceramic w/Shims; Front", 80.05M);
                parts[36] = new PartDescription(683064, 2000, "Toyota",
                    "RAV4 2WD/4-DOOR", "Cooling System",
                    "Radiator Hose; Upper", 103.75M);
                parts[37] = new PartDescription(248759, 1999, "Jeep",
                    "Wrangler Sahara", "Air Intake",
                    "Air Filter", 50.95M);
                parts[38] = new PartDescription(973974, 2007, "Toyota",
                    "Corolla", "Air Intake",
                    "Air Mass Meter; W/o Housing; Meter/sensor only",
                    134.95M);
                parts[39] = new PartDescription(285800, 2001, "Ford",
                    "Escape XLT 4WD", "Transmission",
                    "AT Filter", 34.95M);
                parts[41] = new PartDescription(207495, 2007, "Toyota",
                    "Corolla", "Body Electrical",
                    "Headlight Bulb; 12V 65W; inner-high beam", 9.35M);
                parts[42] = new PartDescription(566676, 2000, "Toyota",
                    "RAV4 2WD/4-DOOR", "Cooling System",
                    "Auxiliary Fan Switch", 42.95M);
                parts[43] = new PartDescription(304950, 2007, "Toyota",
                    "Corolla", "Body Electrical",
                    "Headlight Bulb; 12V 51W; outer", 7.85M);
                parts[44] = new PartDescription(797394, 2000, "Toyota",
                    "RAV4 2WD/4-DOOR", "Cooling System",
                    "Water Flange Gasket", 0.85M);
                parts[45] = new PartDescription(910203, 2007, "Buick",
                    "Lacrosse CXS V6 3.6", "Suspension",
                    "Strut Mount Inc; Sleeve; Rear Right", 80.85M);
                parts[46] = new PartDescription(790794, 2000, "Toyota",
                    "RAV4 2WD/4-DOOR", "Cooling System",
                    "Radiator Hose; Lower", 9.45M);
                parts[47] = new PartDescription(970394, 2007, "Buick",
                    "Lacrosse CXS V6 3.6", "Suspension",
                    "Coil Spring Insulator; Front Lower",
                    14.55M);
                parts[48] = new PartDescription(290840, 2005, "Volvo",
                    "S40 2.5L T5 AWD", "Engine Mechanical",
                    "Rod Bearing Set 1 per Rod; Standard; Reqs. 5-per Engine",
                    26.95M);
                parts[49] = new PartDescription(209704, 2007, "Toyota",
                    "Corolla", "Body Electrical",
                    "Wiper Blade Excel+; Front Right", 7.25M);
                parts[50] = new PartDescription(200368, 2000, "Toyota",
                    "RAV4 2WD/4-DOOR", "Cooling System",
                    "Radiator Drain Plug incl; gasket", 3.15M);
                parts[51] = new PartDescription(200970, 2005, "Volvo",
                    "S40 2.5L T5 AWD", "Engine Mechanical",
                    "Reference Sensor; Flywheel Engine Speed",
                    62.05M);
                parts[52] = new PartDescription(542347, 2007, "Buick",
                    "Lacrosse CXS V6 3.6", "Air Intake",
                    "Air Filter", 50.25M);
                parts[53] = new PartDescription(927045, 2001, "Ford",
                    "Escape XLT 4WD", "Air Intake",
                    "Air Filter", 62.95M);
                parts[54] = new PartDescription(990659, 2000, "Toyota",
                    "RAV4 2WD/4-DOOR", "Cooling System",
                    "Radiator OE Plastic tank", 136.85M);
                parts[55] = new PartDescription(440574, 2007, "Buick",
                    "Lacrosse CXS V6 3.6", "Suspension",
                    "Strut Mount Inc; Sleeve; Rear Left",
                    80.80M);
            }
        }
    }
  5. Return to the form and double-click the Year combo box
  6. To display the list of car makes when the user selects a year, implement the event as follows:
     
    private void cbxCarYears_SelectedIndexChanged(object sender, EventArgs e)
    {
            cbxMakes.Text = "";
            cbxMakes.Items.Clear();
            cbxModels.Text = "";
            cbxModels.Items.Clear();
            cbxCategories.Text = "";
            cbxCategories.Items.Clear();
    
            lbxPartNumbers.Items.Clear();
            lbxPartNames.Items.Clear();
            lbxUnitPrices.Items.Clear();
    
            foreach (PartDescription part in parts)
                    if (part.CarYear == int.Parse(cbxCarYears.Text))
                        if( cbxMakes.FindString(part.Make) == -1 )
                            cbxMakes.Items.Add(part.Make);
    }
  7. Return to the form and double-click the Make combo box
  8. To display the list of car models when the user has selected a year and a make, implement the event as follows:
     
    private void cbxMakes_SelectedIndexChanged(object sender, EventArgs e)
    {
            cbxModels.Text = "";
            cbxModels.Items.Clear();
            cbxCategories.Text = "";
            cbxCategories.Items.Clear();
    
            lbxPartNumbers.Items.Clear();
            lbxPartNames.Items.Clear();
            lbxUnitPrices.Items.Clear();
    
            foreach (PartDescription part in parts)
                    if( (part.CarYear == int.Parse(cbxCarYears.Text)) &&
                        (part.Make == cbxMakes.Text) )
                        if (cbxModels.FindString(part.Model) == -1)
                            cbxModels.Items.Add(part.Model);
    }
  9. Return to the form and double-click the Model combo box
  10. To display the list of categories after the user has selected the year, the make, and the model, implement the event as follows:
     
    private void cbxModels_SelectedIndexChanged(object sender, EventArgs e)
    {
            lbxPartNumbers.Items.Clear();
            lbxPartNames.Items.Clear();
            lbxUnitPrices.Items.Clear();
    
            foreach (PartDescription part in parts)
                    if ((part.CarYear == int.Parse(cbxCarYears.Text)) &&
                        (part.Make == cbxMakes.Text) &&
                        (part.Model == cbxModels.Text) )
                        if (cbxCategories.FindString(part.Category) == -1)
                            cbxCategories.Items.Add(part.Category);
    }
  11. Return to the form and double-click the Category combo box
  12. To display the list of available parts, implement the event and define a new method  as follows:
     
    private void cbxCategories_SelectedIndexChanged(object sender, EventArgs e)
    {
            lbxPartNumbers.Items.Clear();
            lbxPartNames.Items.Clear();
            lbxUnitPrices.Items.Clear();
    
            foreach (PartDescription part in parts)
                if ((part.CarYear == int.Parse(cbxCarYears.Text)) &&
                        (part.Make == cbxMakes.Text) &&
                        (part.Model == cbxModels.Text) &&
                        (part.Category == cbxCategories.Text))
                {
                        lbxPartNumbers.Items.Add(part.PartNumber.ToString());
                        lbxPartNames.Items.Add(part.PartName);
                        lbxUnitPrices.Items.Add(part.UnitPrice.ToString());
                }
    }
  13. Return to the form and double-click the lbxPartNumbers list box
  14. When the user clicks an item from the Part Numbers list box, to make sure the corresponding item is selected in the other list boxes, implement the event as follows:
     
    private void lbxPartNumbers_SelectedIndexChanged(object sender, EventArgs e)
    {
            lbxUnitPrices.SelectedIndex =
                    lbxPartNames.SelectedIndex =
                    lbxPartNumbers.SelectedIndex;
    }
  15. Return to the form and double-click the lbxPartNames list box
  16. Implement the event as follows:
     
    private void lbxPartNames_SelectedIndexChanged(object sender, EventArgs e)
    {
            lbxPartNumbers.SelectedIndex =
                    lbxUnitPrices.SelectedIndex =
                    lbxPartNames.SelectedIndex;
    }
  17. Return to the form and double-click the lbxUnitPrices list box
  18. Implement the event as follows:
     
    private void lbxUnitPrices_SelectedIndexChanged(object sender, EventArgs e)
    {
                lbxPartNames.SelectedIndex =
                    lbxPartNumbers.SelectedIndex =
                    lbxUnitPrices.SelectedIndex;
    }
  19. Return to the form and click (once) the lbxPartNumbers list combo box
  20. In the Properties window, click the Events button and, in the Events section, double-click DoubleClick
  21. Implement the event as follows:
     
    internal void CalculateOrder()
    {
            // Calculate the current total order and update the order
            decimal subTotal1 = 0.00M, subTotal2 = 0.00M, subTotal3 = 0.00M,
                        subTotal4 = 0.00M, subTotal5 = 0.00M, subTotal6 = 0.00M;
            decimal orderTotal = 0.00M;
    
            // Retrieve the value of each sub total
            try
            {
                    subTotal1 = decimal.Parse(this.txtSubTotal1.Text);
            }
            catch (FormatException)
            {
                    MessageBox.Show("Invalid Value");
            }
    
            try
            {
                    subTotal2 = decimal.Parse(this.txtSubTotal2.Text);
            }
            catch (FormatException)
            {
                    MessageBox.Show("Invalid Value");
            }
    
            try
            {
                    subTotal3 = decimal.Parse(this.txtSubTotal3.Text);
            }
            catch (FormatException)
            {
                    MessageBox.Show("Invalid Value");
            }
    
            try
            {
                    subTotal4 = decimal.Parse(this.txtSubTotal4.Text);
            }
            catch (FormatException)
            {
                    MessageBox.Show("Invalid Value");
            }
    
            try
            {
                    subTotal5 = decimal.Parse(this.txtSubTotal5.Text);
            }
            catch (FormatException)
            {
                    MessageBox.Show("Invalid Value");
            }
    
            try
            {
                    subTotal6 = decimal.Parse(this.txtSubTotal6.Text);
            }
            catch (FormatException)
            {
                    MessageBox.Show("Invalid Value");
            }
    
            // Calculate the total value of the sub totals
            orderTotal = subTotal1 + subTotal2 + subTotal3 +
                                 subTotal4 + subTotal5 + subTotal6;
    
            // Display the total order in the appropriate text box
            this.txtTotalOrder.Text = orderTotal.ToString();
    }
    
    private void lbxPartNumbers_DoubleClick(object sender, EventArgs e)
    {
            if (txtPartNumber1.Text == "")
            {
                    // Display the item number in the Part # text box
                    txtPartNumber1.Text = (string)lbxPartNumbers.SelectedItem;
                    // Display the name of the selected item in
                    // the current Description text box
                    txtPartName1.Text = (string)lbxPartNames.SelectedItem;
                    // Display the unit price of this item in
                    // the corresponding Unit Price text box
                    txtUnitPrice1.Text = (string)lbxUnitPrices.SelectedItem;
                    // Since an item was selected, set its quantity to 1
                    txtQuantity1.Text = "1";
                    // Calculate the sub total of the current item item
                    txtSubTotal1.Text = txtUnitPrice1.Text;
                    // Give focus to the Qty text box of the current item
                    txtQuantity1.Focus();
            }// If the previous Part # text box is not empty, then use the next one
            else if (txtPartNumber2.Text == "")
            {
                    txtPartNumber2.Text = (string)lbxPartNumbers.SelectedItem;
                    txtPartName2.Text = (string)lbxPartNames.SelectedItem;
                    txtUnitPrice2.Text = (string)lbxUnitPrices.SelectedItem;
    
                    txtQuantity2.Text = "1";
                    txtSubTotal2.Text = txtUnitPrice2.Text;
                    txtQuantity2.Focus();
            }
            else if (txtPartNumber3.Text == "")
            {
                    txtPartNumber3.Text = (string)lbxPartNumbers.SelectedItem;
                    txtPartName3.Text = (string)lbxPartNames.SelectedItem;
                    txtUnitPrice3.Text = (string)lbxUnitPrices.SelectedItem;
    
                    txtQuantity3.Text = "1";
                    txtSubTotal3.Text = txtUnitPrice3.Text;
                    txtQuantity3.Focus();
            }
            else if (txtPartNumber4.Text == "")
            {
                    txtPartNumber4.Text = (string)lbxPartNumbers.SelectedItem;
                    txtPartName4.Text = (string)lbxPartNames.SelectedItem;
                    txtUnitPrice4.Text = (string)lbxUnitPrices.SelectedItem;
    
                    txtQuantity4.Text = "1";
                    txtSubTotal4.Text = txtUnitPrice4.Text;
                    txtQuantity4.Focus();
            }
            else if (txtPartNumber5.Text == "")
            {
                    txtPartNumber5.Text = (string)lbxPartNumbers.SelectedItem;
                    txtPartName5.Text = (string)lbxPartNames.SelectedItem;
                    txtUnitPrice5.Text = (string)lbxUnitPrices.SelectedItem;
    
                    txtQuantity5.Text = "1";
                    txtSubTotal5.Text = txtUnitPrice5.Text;
                    txtQuantity5.Focus();
            }
            else if (txtPartNumber6.Text == "")
            {
                    txtPartNumber6.Text = (string)lbxPartNumbers.SelectedItem;
                    txtPartName6.Text = (string)lbxPartNames.SelectedItem;
                    txtUnitPrice6.Text = (string)lbxUnitPrices.SelectedItem;
    
                    txtQuantity6.Text = "1";
                    txtSubTotal6.Text = txtUnitPrice6.Text;
                    txtQuantity6.Focus();
            } // If all Part # text boxes are filled, don't do anything
            else
                    return;
    
            CalculateOrder();
    }
  22. Return to the form and click (once) the lbxPartNames list box
  23. In the Events section of the Properties window, double-click Double-Click
  24. Implement the event as follows:
     
    private void lbxPartNames_DoubleClick(object sender, EventArgs e)
    {
            // This event should have been fired already
            // But we call it just to be on the safe side
            lbxPartNames_SelectedIndexChanged(sender, e);
            // Now behave as if the Part Numbers list box was double-clicked
            lbxPartNumbers_DoubleClick(sender, e);
    }
  25. Return to the form and click (once) the lbxUnitPrices list box
  26. In the Events section of the Properties window, double-click Double-Click
  27. Implement the event as follows:
     
    private void lbxUnitPrices_DoubleClick(object sender, EventArgs e)
    {
            lbxUnitPrices_SelectedIndexChanged(sender, e);
            lbxPartNumbers_DoubleClick(sender, e);
    }
  28. Display the form and click the first text box under Qty
  29. In the Properties window and in the Events section, double-click the Leave field
  30. Implement the event as follows:
     
    private void txtQuantity1_Leave(object sender, EventArgs e)
    {
                int qty = 0;
                decimal unitPrice = 0.00M, subTotal = 0.00M;
    
                // Get the quantity of the current item
                try
                {
                    qty = int.Parse(this.txtQuantity1.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                // Get the unit price of the current item
                try
                {
                    unitPrice = decimal.Parse(this.txtUnitPrice1.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                // Calculate the current sub total
                subTotal = qty * unitPrice;
    
                // Display the new sub total in the corresponding text box
                this.txtSubTotal1.Text = subTotal.ToString();
                // Update the order
                CalculateOrder();
    }
  31. Return to the form and click the second text box under Qty
  32. In the Events section of the Properties window, double-click the Leave field and implement the event as follows:
     
    private void txtQuantity2_Leave(object sender, EventArgs e)
    {
                int qty = 0;
                decimal unitPrice = 0.00M, subTotal = 0.00M;
    
                try
                {
                    qty = int.Parse(this.txtQuantity2.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                try
                {
                    unitPrice = decimal.Parse(this.txtUnitPrice2.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                subTotal = qty * unitPrice;
                this.txtSubTotal2.Text = subTotal.ToString();
                
                CalculateOrder();
    }
  33. Return to the form and click the third text box under Qty
  34. In the Events section of the Properties window, double-click the Leave field and implement the event as follows:
     
    private void txtQuantity3_Leave(object sender, EventArgs e)
    {
                int qty = 0;
                decimal unitPrice = 0.00M, subTotal = 0.00M;
    
                try
                {
                    qty = int.Parse(this.txtQuantity3.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                try
                {
                    unitPrice = decimal.Parse(this.txtUnitPrice3.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                subTotal = qty * unitPrice;
                this.txtSubTotal3.Text = subTotal.ToString();
    
                CalculateOrder();
    }
  35. Return to the form and click the fourth text box under Qty
  36. In the Events section of the Properties window, double-click the Leave field and implement the event as follows:
     
    private void txtQuantity4_Leave(object sender, EventArgs e)
    {
                int qty = 0;
                decimal unitPrice = 0.00M, subTotal = 0.00M;
    
                try
                {
                    qty = int.Parse(this.txtQuantity4.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                try
                {
                    unitPrice = decimal.Parse(this.txtUnitPrice4.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                subTotal = qty * unitPrice;
                this.txtSubTotal4.Text = subTotal.ToString();
    
                CalculateOrder();
    }
  37. Return to the form and click the fifth text box under Qty
  38. In the Events section of the Properties window, double-click the Leave field and implement the event as follows:
     
    private void txtQuantity5_Leave(object sender, EventArgs e)
    {
                int qty = 0;
                decimal unitPrice = 0.00M, subTotal = 0.00M;
    
                try
                {
                    qty = int.Parse(this.txtQuantity5.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                try
                {
                    unitPrice = decimal.Parse(this.txtUnitPrice5.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                subTotal = qty * unitPrice;
                this.txtSubTotal5.Text = subTotal.ToString();
    
                CalculateOrder();
    }
  39. Return to the form and click the sixth text box under Qty
  40. In the Events section of the Properties window, double-click the Leave field and implement the event as follows:
     
    private void txtQuantity6_Leave(object sender, EventArgs e)
    {
                int qty = 0;
                decimal unitPrice = 0.00M, subTotal = 0.00M;
    
                try
                {
                    qty = int.Parse(this.txtQuantity6.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                try
                {
                    unitPrice = decimal.Parse(this.txtUnitPrice6.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                subTotal = qty * unitPrice;
                this.txtSubTotal6.Text = subTotal.ToString();
    
                CalculateOrder();
    }
  41. Return to the form
  42. Double-click the first Remove button and implement its event as follows:
     
    private void btnRemove1_Click(object sender, EventArgs e)
    {
            txtPartNumber1.Text = "";
            txtPartName1.Text = "";
            txtUnitPrice1.Text = "0.00";
            txtQuantity1.Text = "0";
            txtSubTotal1.Text = "0.00";
            CalculateOrder();
    }
  43. Return to the form
  44. Double-click the second Remove button and implement its event as follows:
     
    private void btnRemove2_Click(object sender, EventArgs e)
    {
            txtPartNumber2.Text = "";
            txtPartName2.Text = "";
            txtUnitPrice2.Text = "0.00";
            txtQuantity2.Text = "0";
            txtSubTotal2.Text = "0.00";
            CalculateOrder();
    }
  45. Return to the form
  46. Double-click the third Remove button and implement its event as follows:
     
    private void btnRemove3_Click(object sender, EventArgs e)
    {
            txtPartNumber3.Text = "";
            txtPartName3.Text = "";
            txtUnitPrice3.Text = "0.00";
            txtQuantity3.Text = "0";
            txtSubTotal3.Text = "0.00";
            CalculateOrder();
    }
  47. Return to the form
  48. Double-click the fourth Remove button and implement its event as follows:
     
    private void btnRemove4_Click(object sender, EventArgs e)
    {
            txtPartNumber4.Text = "";
            txtPartName4.Text = "";
            txtUnitPrice4.Text = "0.00";
            txtQuantity4.Text = "0";
            txtSubTotal4.Text = "0.00";
            CalculateOrder();
    }
  49. Return to the form
  50. Double-click the fifth Remove button and implement its event as follows:
     
    private void btnRemove5_Click(object sender, EventArgs e)
    {
            txtPartNumber5.Text = "";
            txtPartName5.Text = "";
            txtUnitPrice5.Text = "0.00";
            txtQuantity5.Text = "0";
            txtSubTotal5.Text = "0.00";
            CalculateOrder();
    }
  51. Return to the form
  52. Double-click the sixth Remove button and implement its event as follows:
     
    private void btnRemove6_Click(object sender, EventArgs e)
    {
            txtPartNumber6.Text = "";
            txtPartName6.Text = "";
            txtUnitPrice6.Text = "0.00";
            txtQuantity6.Text = "0";
            txtSubTotal6.Text = "0.00";
            CalculateOrder();
    }
  53. Return to the form
  54. Double-click the Close button and implement its Click event as follows:
     
    private void btnClose_Click(object sender, EventArgs e)
    {
            Close();
    }
  55. Execute the application to test it
     
    College Park Auto Parts - Form Result
  56. After using it, close the form

Finding a String in the Combo Box

Instead of simply selecting an item from a combo box, the user may want to find out if a certain string exists in the  list. To support this operation, the ComboBox class is equipped with a method named FindString that is overloaded with two versions. One of the syntaxes of this method is:

public int FindString(string s);

This method takes as argument the string to find in the combo box. If the item is found in the list, the method returns its position. If the list does not have that string, the method return -1. The above syntax of the method would look through the whole list. If you want the search to start at a specific index, you can use the following version of the FindString() method:

public int FindString(string s, int startIndex);

This version takes as the first argument a string. Instead of start looking for it from the beginning of the list, this method starts at the index specified by the startIndex value.

The FindString() method performs its operation without regards to case. This means that it would perform the same search for BlindMan, Blindman, blindMan, or BLINDMAN and would produce the same result for them. If you want the case of the characters to be taken into consideration, use the FindStringExact() method that also is overloaded with two versions. The syntax of the first version is:

public int FindStringExact(string s);

This method proceeds like the FindString() method by starting to look for the string from the beginning of the list. If you want to specify from where to start looking for the string, you should use the following version:

public int FindStringExact(string s, int startIndex);

 

 

Previous Copyright © 2007-2012 FunctionX Next