Results 1 to 5 of 5

Thread: [2005] Creating subroutines

  1. #1

    Thread Starter
    PowerPoster Pasvorto's Avatar
    Join Date
    Oct 2002
    Location
    Minnesota, USA
    Posts
    2,951

    [2005] Creating subroutines

    OK, so I have a bunch of fields that I need to validate (numeric). Does anyone have sample code of a subroutine where I could just send it the field name and it could test the field for non-numeric value?

    In the spirit of 'good programming', this validation code should only exist in one place. In the C# world, would that be a class? I thought I read somewhere that there aren't any 'global' subroutines (like VB)

    This is my current (repeated many times) code:

    string strScore;
    int intScore;
    strScore = txtPayment.Text;
    bool blnInput;
    blnInput = Int32.TryParse(strScore, out intScore);
    If (blnInput == false)
    .....MessageBox.Show("Field must be numeric", "TVAL", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
    ===================================================
    If your question has been answered, mark the thread as [RESOLVED]

  2. #2
    Registered User nmadd's Avatar
    Join Date
    Jun 2007
    Location
    U.S.A.
    Posts
    1,676

    Re: [2005] Creating subroutines

    If that code won't return anything and you're just checking for an integer, you can place that code in a void method. Just as you would place it in a subroutine in VB.

    c# Code:
    1. // Check for an integer.
    2.         private void CheckForInteger(string score)
    3.         {
    4.             int result;
    5.             if (!Int32.TryParse(score, out result))
    6.             {
    7.                 MessageBox.Show("Not an integer.");
    8.             }
    9.         }

    Then, again like in VB, call it whenever you need to:
    c# Code:
    1. // Call my method.
    2.         private void button1_Click(object sender, EventArgs e)
    3.         {
    4.             CheckForInteger(this.textBox1.Text);
    5.         }

    Here is some great help for C#:
    http://msdn2.microsoft.com/en-us/lib...11(VS.80).aspx

    Hope that helps.

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [2005] Creating subroutines

    As has been said, the C# equivalent of a VB procedure (Sub) is a function with a void return type. Also, the C# equivalent of a VB module is a static class.

    I'd be inclined to use a boolean function in this case though:
    C# Code:
    1. public bool ValidateInteger(string val)
    2. {
    3.     bool result = false;
    4.     int number;
    5.  
    6.     if (int.TryParse(val, number))
    7.     {
    8.         result = true;
    9.     }
    10.     else
    11.     {
    12.         MessageBox.Show("Please enter an integer value",
    13.                         "Invalid Input",
    14.                         MessageBoxButtons.OK,
    15.                         MessageBoxIcon.Warning);
    16.     }
    17.  
    18.     return result;
    19. }
    That combines validation and returning the result with displaying the error message if it fails. What it doesn't do is give you the numeric value, which is the problem with centralised validation like that. You can't get an integer and a boolean returned. That's why TryParse has the number passed by reference, but if you were going to try that yourself then you may as well just use TryParse directly each time.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  4. #4
    Hyperactive Member
    Join Date
    Dec 2002
    Location
    The Big D
    Posts
    310

    Re: [2005] Creating subroutines

    Here is a general validation class I have been using. It uses regex for the actual validations.

    Code:
    using System;
    using System.Collections.Generic;
    using System.Text.RegularExpressions ;
    
    namespace Utilities
    {
        /// <summary>
        /// Basic data validation class
        /// </summary>
        public class Validation    
        {
            /// <summary>
            /// Enumeration of validation types
            /// </summary>
            public enum PatternTypes
            {
                /// <summary>
                /// General regex numeric test
                /// </summary>
                Numeric,
    
                /// <summary>
                /// General regex phone number test
                /// </summary>
                Phone,
    
                /// <summary>
                /// General regex zip code test
                /// </summary>
                Zipcode,
    
                /// <summary>
                /// General regex email address test
                /// </summary>
                Email
            }
    
            #region REGEX Patterns
            private const string Numeric = @"(^[-+]?\d+(,?\d*)*\.?\d*([Ee][-+]\d*)?$)|(^[-+]?\d?(,?\d*)*\.\d+([Ee][-+]\d*)?$)";
            private const string Phone = @"^\d{10}$";
            private const string Zipcode = @"^\d{5}$";
            private const string Email = @"^(([^<>()[\]\\.,;:\s@\""]+"
                            + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                            + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                            + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                            + @"[a-zA-Z]{2,}))$";
            #endregion
    
            /// <summary>
            /// Main validation method. Depending on valiation type
            /// it sets a regex pattern and validates the data against it.
            /// </summary>
            /// <param name="Value">String value to be validated</param>
            /// <param name="Type">Item from PatternTypes enumeration</param>
            /// <returns>Boolean - Success/Fail</returns>
            public bool Validate(string Value, PatternTypes Type)
            {
                string pattern = "";
    
                switch (Type)
                {
                    case PatternTypes.Numeric:
                        pattern = Numeric;
                        break;
    
                    case PatternTypes.Phone:
                        pattern = Phone ;
                        break;
    
                    case PatternTypes.Zipcode:
                        pattern = Zipcode ;
                        break;
     
                    case PatternTypes.Email:
                        pattern = Email ;
                        break;
      
                    default:
                        break;            
                }
    
                string patternStrict = pattern;
                Regex reStrict = new Regex(patternStrict);
                if (!reStrict.IsMatch(Value))
                    return false;
    
                return true;
            }
    
            /// <summary>
            /// Very basic IsNumeric method
            /// </summary>
            /// <param name="Value">String value to be validated</param>
            /// <returns>Boolean - Success/Fail</returns>
            public bool IsNumeric(string Value)
            {
                string patternStrict = Numeric;   
                Regex reStrict = new Regex(patternStrict);
                if (!reStrict.IsMatch(Value))
                    return false;
                return true;
            }
    
            /// <summary>
            /// Combines an isnumeric check with an empty value check
            /// </summary>
            /// <param name="Value">String value to be validated</param>
            /// <returns>Boolean - Success/Fail</returns>
            public bool ValidateGeneral(string Value)
            {
                if (IsNumeric(Value) || Value.Length == 0)
                    return false;
                else
                    return true;
            }
        }
    }

  5. #5

    Thread Starter
    PowerPoster Pasvorto's Avatar
    Join Date
    Oct 2002
    Location
    Minnesota, USA
    Posts
    2,951

    Re: [2005] Creating subroutines

    Thanks for the input folks. Most helpful. Got to play with "subroutines" now.
    ===================================================
    If your question has been answered, mark the thread as [RESOLVED]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width