Zebra0.com

csharp arrays

Continue with the Color project and modify the code as shown below:

//Programmer: Janet Joy
//Use  parallel arrays of colors
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ColorCombo
{
    public partial class Form1 : Form
    {
        // Two arrays that are related to each other are called parallel arrays.
        // For this project make sure the sorted property of the combo box is false.
        string[] myColors = { "red", "yellow", "blue", "white" }; //text will go in combo box
        Color[] colors = { Color.Red, Color.Yellow, Color.Blue, Color.White };
        public Form1()
        {
            InitializeComponent();
        }

        private void cboColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Get the index of the selected item and use as index to array
            int num = cboColor.SelectedIndex;
            this.BackColor = colors[num];
            this.Text = myColors[num]; //either this line or one below will work
            this.Text = cboColor.Text; //You don't need both.
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Add each of the colors from the array to the combo box
            for (int i = 0; i < myColors.Length; i++)
            {
                cboColor.Items.Add(myColors[i]);
            }
            cboColor.SelectedIndex = 0;
        }
    }
}

End of lesson, Next lesson: Dialogs in C#