WinForm TextBox extension Method data validation

Source: Internet
Author: User

This article reproduced: http://www.cnblogs.com/gis-crazy/archive/2013/03/17/2964132.html

When looking at the company project code, there is a problem: WinForm interface has a lot of information to fill, submit background server updates, but the data of the legitimate validation and value conversion is not too much to compliment, a pile of if judgment and conversion, then think about whether to expand a method out, to figure out a train of thought, record down with everyone to discuss , there is a wrong place also ask you to correct me.

Design ideas:
1. Since most of the data values are obtained from the TextBox control, you can extend the generic method to get the value directly based on the converted data type, like this,
var value = this.txtsample.getvalue<int> ();

2. You can pass in a delegate to handle the operation that the conversion failed, and overload this method to provide a default action.

OK, here's the start:
1. Create an extension method for the TextBox type
Refer to MSDN's explanation:Extension methods enable you to "add" methods to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type.An extension method is a special static method, but it can be called just like an instance method on an extended type.For client code written in C # and Visual Basic, there is no significant difference between calling extension methods and calling methods that are actually defined in the type.
       extension methods are defined as static methods, but they are called through the instance method syntax. Their first argument specifies which type the method acts on, and the parameter is prefixed with the This modifier. extension methods are only in scope when you explicitly import namespaces into the source code using a using directive.
Note: The extension method is defined inside a non-nested, non-generic static class

2. Because the conversion type is unknown, but is a value type, the generic method is designed, and with the strut generic constraint, due to allow the operation of the custom processing transformation fails, it is passed into an action delegate to implement, as follows:

public static TResult getvalue<tresult> (this textbox textbox, Action<textbox> failed)            where TResult: struct        {            var type = typeof (TResult);            var method = type. GetMethod ("TryParse", new type[] {typeof (String), Type. Makebyreftype ()});            var parameters = new Object[] {textbox.text, default (TResult)};            If the conversion fails, execute failed            if (!) ( BOOL) method. Invoke (null, parameters))            {                failed (TextBox);                throw new InvalidCastException ("The input value is malformed, please check the input value.") ");            }            Return (TResult) parameters[1];        }

    here uses a reflection mechanism to invoke the type of T.tryparse (string param, out T value), such as Int32.TryParse (string param,out Int32 Valu e) and so on, it should be noted that:
(1). GetMethod () method, you must pass in the appropriate parameter (the signature of the method to reflect) to determine the method is unique, such as encountering overloading this case (more common), otherwise the return value is null, the signature of the method, if the parameter has a ref or out keyword, Type needs to be added with. Makebyreftype (), as above.
(2). After you get the unique method instance, you can pass in the corresponding parameter, call the Invoke method to implement the method call, Methodinfo.invoke (Object obj, object[] Parameters) method The first argument calls the method for reflection Object, if it is a static method (for example, in this case), you can pass in NULL, the second parameter is the parameter of the method, and the order must match the method signature.
(3). The method parameter is provided with the ref and out keyword, and the value is obtained by the parameter array. As in this example: Parameters[1]

3. Defining a delegate for a conversion failure operation
There are two types of delegates in C # built-in encapsulation, action and Func delegates, and there are many overloaded versions with parameters that can be more than 10, so don't worry about parameter issues. Where the action delegate has no return value, is of type void, and the Func delegate has a return value, such as FUNC<T,TRESULT>, which is common in LINQ operations, where there is no need to return a value, the action delegate is used because the operation that the conversion failed is required to handle , the textbox is processed as a parameter to the delegate, as shown in the code, when the conversion fails:
If the conversion fails, execute failed
if (! ( BOOL) method. Invoke (null, parameters))
Failed (TextBox);
Here is a simple introduction to the delegate: the delegate is actually a type, through the Anti-compilation tool can be seen, when the construction of a delegate to a method, in fact, will be invisible to the two parameters (TARGET,METHODPTR), the target parameter is to invoke the method instance, if the static method, then null, Methodptr is the memory address of the incoming method (the information is stored in metadata), Faild (TextBox) surface is not very good understanding, why an object with a parameter, in fact, the C # compiler for us to do a lot of work, here in essence is faild. Invoke (TextBox), it's good to understand that the delegate is a type that invokes the method registered by the delegate through the Faild delegate object.

4. Create the overloaded version:
Use a lambda expression to define the default conversion failure action, and if the conversion fails, prompt the message and select all and navigate to the input box.

public static TResult getvalue<tresult> (this textbox textbox, bool Isshowerror)            where tresult:struct        { C3/>return getvalue<tresult> (textBox, p = =            {                if (isshowerror)                {                    p.focus ();                    P.selectall ();                    MessageBox.Show ("Input value format is not correct, please re-enter!") ",                        " hint--value type: "+ typeof (TResult). Name,                        MessageBoxButtons.OK, messageboxicon.warning);                }            );}        

Default version, calling the previous overloaded method
public static TResult getvalue<tresult> (this textbox textbox) where Tresult:struct { return Getvalue<tresult> (TextBox, True); }

5. Experimental test:
New WinForm Program, interface:

Background code:

private void Btnconvert_click (object sender, EventArgs e)        {            try            {                var intvalue = txtint.getvalue< Int> ();                var floatvalue = txtfloat.getvalue<float> ();                var datetimevalue = txtdatetime.getvalue<datetime> ();                var doublevalue = txtdouble.getvalue<double> ();            }            catch (Exception) {}        }

If the input value is illegal, an error is indicated:

Reprint Please specify source: http://www.cnblogs.com/gis-crazy/archive/2013/03/17/2964132.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.