p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   BOOK: Stephens' C# Programming with Visual Studio 2010 24-Hour Trainer (http://p2p.wrox.com/forumdisplay.php?f=574)
-   -   Chapter 10 Exercise 3 Alternative Solution (http://p2p.wrox.com/showthread.php?t=92160)

benhelfman February 10th, 2014 06:34 PM

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);
        }
    }


Rod Stephens February 10th, 2014 06:50 PM

That's a good solution.

More generally, if you have a method such as this one that you plan to reuse in many solutions, you should put it in a class library project. Then you can add references to that project to the others and use the method in the library much as you did here.


All times are GMT -4. The time now is 08:11 PM.

Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.