简体   繁体   中英

Validation of c# winform controls that are bounded to an object

I created winform controls in my app using the toolbox. I also set default value, min and max of those controls in the settings page. Then, I bounded those controls in an object. Something that looks like this:

 private void InitializeBinding()
    {
        enable_checkbox.DataBindings.Add("Checked", ObjectConfig, "enable");
        area_numeric.DataBindings.Add("Value", ObjectConfig, "area");

    }

and my ObjectConfig class have this:

class ObjectConfig {
   private bool bEnable;
   private int iArea;

   public bool enable
   {
     get { return bEnable; }
     set { bEnable = value; }
   }

   public int area
   {
     get { return iArea; }
     set { iArea = value; }
   }
}

The binding is working great. No problems whatsoever. Then, I am converting this object to xml and I am saving it to a config xml file.The problem is that if someone edited the value of area in the xml file to a number that goes beyond the set min and max value and the xml is loaded and converted to an object, there is an error since the object is binded to a control with min and max value. Is there a good way to provide validation in this type of approach?

You can constraint it in the setter of the property and check there whether it is within the limits. You can put the limit values into project properties variables like this (sorry for the German version Dictionary ):

在此处输入图片说明

And in the setter you can check these ranges and acces the variables like the following:

public class ObjectConfig
{
    private bool bEnable;
    private int iArea;

    public bool enable
    {
        get { return bEnable; }
        set { bEnable = value; }
    }

    public int area
    {
        get { return iArea; }
        set
        {
            if (value < Properties.Settings.Default.AreaMin)
            {
                iArea = Properties.Settings.Default.AreaMin;
            }
            else if (value > Properties.Settings.Default.AreaMax)
            {
                iArea = Properties.Settings.Default.AreaMax;
            }
            else
            {
                iArea = value;
            }
        }
    }
}

This way your values will always within the set range irrespective of what the user edits in the *.XML file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM