View Single Post
  #1 (permalink)  
Old February 10th, 2014, 06:34 PM
benhelfman benhelfman is offline
Registered User
Points: 10, Level: 1
Points: 10, Level: 1 Points: 10, Level: 1 Points: 10, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Dec 2012
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Default Chapter 10 Exercise 3 Alternative Solution

Per the comment in the exercise reminding us that we had already written a colorsamples selector in an earlier lesson, I wrote a version of the above exercise by adding a reference to the earlier project rather than copy and past it. This code is not perfect but I thought I would share it.

I made the sampleColorLabel public and encapsulated the code to call the dialog in a helper method which references the Namespace of the previous project.

Code:
        //Current foreground or background color passed in.
        private Color displayDialog(Color color)
        {
            ColorSamples.ColorSamples colorSamplesDialog;
            colorSamplesDialog = new ColorSamples.ColorSamples();

            
            if (colorSamplesDialog.ShowDialog() == DialogResult.OK)
            {
                //If OK is selected return the new color
                return colorSamplesDialog.sampleLabel.BackColor;
            }

            else
            {
                //otherwise return the same color passed in (no change in color).
                return color;
            }
        }
I then call this helper method from each of the buttons:

Code:
       private void foreColorButton_Click(object sender, EventArgs e)
        {
            //Call dialog.  OK: new color 
            //Cancel: return the current ForeColor, resulting in no change.
            this.ForeColor = displayDialog(this.ForeColor);
        }

        private void backColorButton_Click(object sender, EventArgs e)
        {
            //Call dialog.  OK: new color
            //Cancel: return the current ForeColor, resulting in no change.
            this.BackColor = displayDialog(this.BackColor);
        }
    }