methods

A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. (msdn)

. Hello()
Can create YOUR OWN method that can be called many times in many places. Avoids repeating code over and over in multiple places - write once - test once - modify once

      // simple 
      private void Hello()
      {
         MessageBox.Show( "Hello" );
      }
      //call: 
      Hello();
      
      
      // overloaded method
      private void Hello( string Person )
      {
         MessageBox.Show( "Hello " + Person );
      }      
      //call: 
      Hello("Betty");
           
      
      // pass a textbox
      private void Hello( string Person, TextBox t )
      {
         t.Text =  "Hello " + Person;
      }
      // call: 
      Hello("Bill", txtName);

. ExitProgram()
Can create YOUR OWN method that can be called many times in many places. Avoids repeating code over and over in multiple places - write once - test once - modify once
      public void ExitProgram( )
      {
         // result of dialog MUST be this type
         DialogResult result;

         // show a message box and get answer
         result = MessageBox.Show( "Want to exit? ",              // msg
                                   "Exiting!",                    // caption
                                   MessageBoxButtons.YesNoCancel, // buttons
                                   MessageBoxIcon.Warning);       // icon

         // exit if YES
         if (result == DialogResult.Yes)
            this.Dispose();
      }

      //call   
      ExitProgram();

. Returning a value

      private int Sum( int num1, int num2 )
      {
         int answer;
         
        // calculate and return the value
         answer = num1 + num2;
         return answer;
      }
      
      //call: 
      x = Sum( 3, 4 );
      x = Sum( 1, 1 );
      x = Sum( a, b );
      x = Sum( Sum(2,3), 8);

      

      private int SumRange( int num1, int num2 )
      {
         int answer=0;

        // calculate and return the value
         for(int i=num1; i<=num2; i++)
            answer += i;
         return answer;
      }
      
What is the scope of variable 'answer'? Lifetime? How about 'i'?? How do you call this method?

. FileToList(): file dialog, file open and write to listbox


      private void FileToList( ListBox lst )
      {
         string s; // will hold each line of the file as each is read
      
         // Show the open file dialog box & get file name
         if ( openFileDialog1.ShowDialog() == DialogResult.OK )
         {
            // connect stream to file ( need using System.IO)
            StreamReader reader = new StreamReader( openFileDialog1.FileName );

            // read the file (one line at a time) and show in listbox
            while( !reader.EndOfStream )
            {
               s = reader.ReadLine();
               lst.Items.Add(s);
            }            
           reader.Close( );            
         }         
      }

. Windows: ReadPositiveInt() - pass in a TextBox control object, return an int
This method has ONE parameter - a TextBox. And the "int" means it RETURNS an int value.
      // reads an int from the specified textBox 
      // if ok, return the converted num
      // otherwise return a -1 indicating an error 
      public int ReadPositiveInt( TextBox t )
      {
         int num;

         // gets string from textBox, t
         string s = t.Text;

         // returns converted number if it is valid
         if ( int.TryParse(s, out num) == true )
            return num;
         else
         {
            // parse NOT successful
            MessageBox.Show( t.Text + " is an illegal value - try again.");
            t.Focus();
            return -1;
         }
      }
   
      // call the method when button clicked
      // note that the error message is handled in the called method
      private void btnRetire_Click(object sender, EventArgs e)
      {
         int age = ReadPositiveInt( txtIn );

         // check if valid
         if( age != -1 )
         {
           if( age <= 65 )
             MessageBox.Show( "Age: " + age.ToString() + " too young to retire!" );
           else
             CalculatePension( age );
         }
      }

This console program uses a method with ONE parameter - a string. RETURNS an int value.
     // console program
     class Program
     {
         static void Main( )
         {
             int temp = ReadInt( "Enter the temperature");
             int weight = ReadInt( "Enter your weight");
             int age = ReadInt( "Enter your age");
         }
         
         static int ReadInt( string prompt ) 
         {
            string s;
            int num;

            do // keep looping while can't convert
            {
               Console.Write( prompt + ": " );
               s =  Console.ReadLine( );
            } while ( int.TryParse( s, out num ) != true );

            // got a good #, so return it
            return num;
         }
     } 

. Create a web page for output
   //
   // creates a web page to display the two values passed in as parameters
   // displays the web page in the default browser
   static void WriteToWebPage(long sum, int count)
   {
      // to create an html file - name must end in ".html"
      StreamWriter writer = new StreamWriter("output.html");
      
      // create the html page head - this is html5
      writer.WriteLine("<!doctype html>");
      writer.WriteLine("<html>");
      writer.WriteLine("<head>"); 
      writer.WriteLine("<title>Output</title>");
      writer.WriteLine("<meta charset="UTF-8" />");
      writer.WriteLine("</head>");

      // create the html page body      
      writer.WriteLine("<body>");

      // web content here
      writer.WriteLine("<h1>"Output"</h1>"); 
      writer.WriteLine("<h2>Sum:" + sum + "  ·  Count:" + count + "</h1>"); 
      writer.WriteLine("<hr />"); 
      
      // end the html page
      writer.WriteLine("</body>"); 
      writer.WriteLine("</html>");
      
      // close the html file
      writer.Flush();
      writer.Close();
      
      // start the default web browser and display
      System.Diagnostics.Process.Start("output.html"); // or "using System.Diagnostics"
   }
   

. PerformClick() - calling an event procedure
Can "call" an existing event method. Avoids repeating code over and over in multiple places - write once - test once - modify once
      // say hello
      private void btnHello_Click(object sender, EventArgs e)
      {
         MessageBox.Show("Hello!");
      }

      // calls "say hello"
      private void radGreet_CheckedChanged(object sender, EventArgs e)
      {
         btnHello.PerformClick(); // call it
      }
   

      // compute something and report 
      private void btnCompute_Click(object sender, EventArgs e)
      {
         int x = Convert.ToInt32( txtIn1.Text );
         int y = Convert.ToInt32( txtIn2.Text );
         answer = ( x * 2 ) + ( y * 22 );
         MessageBox.Show("Hello! Your answer is: " + answer.ToString("N2") );
      }

      // call the "click" event code
      private void btnOther_Click(object sender, EventArgs e)
      {
         // calls button rather tahn repeat same code
         if( value > 100 )
            btnCompute.PerformClick( );
      }

. Event handlers: "sender" and "e" parameters
When creating event handlers, notice the two parameters, 'sender' and 'e':
    private void button1_Click( object sender, EventArgs e )

sender
======

The sender argument provides info about the event. Tells "who" sent it ( such as a button ) There's a fairly small set of methods that sender provides directly. Equals GetHashCode GetType ToString
      private void button1_Click(object sender, EventArgs e)
      {
         MessageBox.Show( sender.ToString() );
      }
Shows: System.Windows.Forms.Button, Text:button1 Can use this info:
   // see if it was a button
   if( sender.GetType.ToString() == "System.Windows.Forms.Button" )
   {
      ...
   }
   // or was it a textbox?
   else if (sender.GetType.ToString() == "System.Windows.Forms.TextBox" )
   {
      ...
   }

e
===

The argument, e, contains info you may need to process the event. Info depends on the type of event, so it is important to use an event that provides the information you need. e EXAMPLE ======= Get x and y mouse coordinates from mouse move event on button2 Info is contained in "e" e.X e.Y
  private void button2_MouseMove(object sender, MouseEventArgs e)
      {
         // show x coordinate of mouse
         button2.Text = "Mouse location X is: " + e.X.ToString();
      }
## Note: X and Y NOT available in the "e" argument of other events like button clicks...



. Change BackColor - pass in a control object, nothing returned. Method AND Class!
This method changes the BackColor and Text properties of the specified control - the parameter. Note that "void" means that it returns nothing. ============================================================== * This works, BUT, having the rnd object IN the method recreates it every call and when those calls happen quickly, the seed is the same and the random numbers will be the same.
      // changes BackColor & Text of specified control
      private void RandomBackColor( Control O ) // parameter is Control, "O"
      {
         // get random nums
         Random rnd = new Random( );
         int r = rnd.Next( 256 );  // 0-255
         int g = rnd.Next( 256 );
         int b = rnd.Next( 256 );

         // set color and text control properties
         O.BackColor = Color.FromArgb( r, g, b );
         O.Text = r.ToString( ) + ' ' + g.ToString( ) + ' ' + b.ToString( );
      }


      // call the user method to change the colors
      private void button1_Click( object sender, EventArgs e )
      {
         RandomBackColor( button1 );      // argument is button1
         RandomBackColor( label1 );       // argument is label1
         RandomBackColor( radioButton1 ); // argument is radioButton1
         RandomBackColor( pictureBox1 );  // ignores Text property 
      }
   

Create a CLASS - fixes the problem ================================== * This works! Encapsulate the method and the data (the random object) in a class. Make it static so DON'T need to instantiate. Ranom object only seeded ONCE.
      
   public class RColor
   {         
      static Random rnd = new Random();
      
      // changes BackColor & Text of specified control
      public static void RandomBackColor(Control O) // parameter is Control, "O"
      {
         // get random nums
         int r = rnd.Next(256);  // 0-255
         int g = rnd.Next(256);
         int b = rnd.Next(256);

         // set color and text control properties
         O.BackColor = Color.FromArgb(r, g, b);
         O.Text = r.ToString() + ' ' + g.ToString() + ' ' + b.ToString();
      }
   }

   public partial class Form1 : Form
   {
      public Form1()
      {
         InitializeComponent();
      }

      private void button1_Click(object sender, EventArgs e)
      {
         RColor.RandomBackColor(button1);
         RColor.RandomBackColor(this);
      }
   }

. Change Opacity - make a form fade away and return!
This method changes the Opacity property of the specified form - the parameter. Note that "void" means that it returns nothing.
      // cycles Opacity of specified control
      private void Magic( Form f ) // parameter is Form, "f"
      {
         // disappear
         for (double i = 1.0; i >= 0.0; i -= .005)
         {
            f.Opacity = i;
            f.Text = i.ToString();
            f.Refresh();
            System.Threading.Thread.Sleep(5);
         }         
         // pause 3.5 seconds for drama
         System.Threading.Thread.Sleep(3500);    
         
         // reappear
         for (double i = 0.0; i <= 1.0; i += .005)
         {
            f.Opacity = i;
            f.Text = i.ToString();
            f.Refresh();
            System.Threading.Thread.Sleep(5);
         }
      }
      
      
      // call the user method to change the opacity
      private void button1_Click( object sender, EventArgs e )
      {
         Magic( this ) // argument is the current form
      }

. Change Color black to white - gradually - bool return value
This method changes the BackColor property of the specified control - the parameter. Note that "bool" means that it returns either true or false.
      // changes BackColor of specified control
      private bool BtoW( Control o ) // parameter is Control Object, "o"
      {
         // start black, go thru gray to white
         try
         {
            int col = 0;
            do
            {       
               // change color, show color rgb, refresh & pause         
               o.BackColor = Color.FromArgb( col, col, col );
               o.Refresh( );
               o.Text = col.ToString();
               System.Threading.Thread.Sleep( 10 );

            } while( ++col < 256);
            return true;
         }
         // if something went wrong, let caller know         
         catch
         {
            return false;
         }         
      }
      
      
      // call the user method to change the colors
      private void button1_Click( object sender, EventArgs e )
      {
         if( BtoW( button1 ) == false ) // argument is button1
            MessageBox.Show( "error" );
      }



. Graphics: drawing rectangles and ellipses on mouse events
This method has TWO parameters - e (MouseEventArgs ) - o (Control Object) void" means it returns nothing
   
using System;
using System.Drawing;
using System.Windows.Forms;
   
   private void Draw( MouseEventArgs e, Control o )
   {
      // create a random object
      Random rnd = new Random();

      // create a graphics context to draw upon 
      Graphics g = o.CreateGraphics();
      
      // get random values for color and for size
      int R = rnd.Next(256), G = rnd.Next(256), B = rnd.Next(256);
      int W = rnd.Next(10, 120), H = rnd.Next(10, 120);
      
      // if left button down rectangle else ellipse
      if ( e.Button == MouseButtons.Left )
         g.FillRectangle(new SolidBrush(Color.FromArgb(R,G,B)), e.X, e.Y, W, H);
      else
         g.FillEllipse(new SolidBrush(Color.FromArgb(R,G,B)), e.X, e.Y, W, H);
         
      // get rid of graphics context
      g.Dispose();
   }

   
   // call to draw on panel
   private void panDraw_MouseDown(object sender, MouseEventArgs e)
   {
      Draw( e, panDraw);
   }
   
   // call to draw on form
   private void Form1_MouseDown(object sender, MouseEventArgs e)
   {
      Draw( e, this );
   }
   
    // call to draw on form on MOVE
    private void Form1_MouseMove(object sender, MouseEventArgs e)
   {
      Draw(e, this);
   }
# Can also draw on buttons, listboxes, pictureboxes ...

. RECURSION (slick): Loop through all Controls on a form AND the containers (panels, groupboxes)
Loop thru all the controls on the form, INCLUDING those in PANEL or GROUPBOX
   
     private void button1_Click(object sender, EventArgs e)
      {
         Toggle( this, true ); 
      }

      private void Toggle( Control container, bool state)
      {
         // loop thru ALL controls on form 
         foreach( Control c in container.Controls )
            if( c is CheckBox )
            {
               // force the control into a checkButton & uncheck            
               CheckBox cb = (CheckBox)c;
               cb.Checked = state;
            }
            // otherwise try to set all controls in next 
            // "container" - if not a container, then count NOT > 0          
            else if ( c.Controls.Count > 0 )
               Toggle( c, state ); 
      }

. RECURSION (slick): Color all Controls on a form AND the containers (panels, groupboxes)
Loop thru all the controls on the form, INCLUDING those in PANEL or GROUPBOX
   
   // ------------ Color Class --------------- 
   public class RColor
   {         
      static Random rnd = new Random();
      // changes BackColor & Text of specified control 
      public static void randomBackColor(Control O) // parameter is Control, "O"
      {
         // get random nums 
         int r = rnd.Next(256);  // 0-255
         int g = rnd.Next(256);
         int b = rnd.Next(256);

         // set color and text control properties 
         O.BackColor = Color.FromArgb(r, g, b);
         O.Text = r.ToString() + ' ' + g.ToString() + ' ' + b.ToString(); 

         foreach (Control c in O.Controls)
         {
            // get random nums 
            r = rnd.Next(256);  // 0-255
            g = rnd.Next(256);
            b = rnd.Next(256);

            // set color and text control properties 
            c.BackColor = Color.FromArgb(r, g, b);
            c.Text = r.ToString() + ' ' + g.ToString() + ' ' + b.ToString(); 
            
            // otherwise try to set all controls in next 
            // "container" - if not a container, then count NOT > 0               
            if ( c.Controls.Count > 0 )
               randomBackColor(c);
         }
      }
   }