在PropertyGrid中的WinForms内验证PropertyGrid、WinForms

2023-09-06 15:11:06 作者:烟伤肺不伤心

是否有可能实现输入的验证的的WinForms Propertgrid控制范围之内?比如我如何可以验证/定义必填字段?我可以使用错误商? 是否有可能使用 RequiredAttribute标签(System.ComponentModel.DataAnnotations)?

Is it possible to implement input validation within the Winforms Propertgrid control? For example how can I validate/define "required fields"? Can I use the Error Provider? Is it possible to use RequiredAttribute (System.ComponentModel.DataAnnotations)?

推荐答案

注册OnValueChanged事件和做的工作有!

Register OnValueChanged event and do the work there!

propertyGrid.PropertyValueChanged+=  new PropertyValueChangedEventHandler(propertyGrid_PropertyValueChanged ); 


private void propertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) 
    { 
        if (e.ChangedItem.Label == "???" && !IsValid((int)e.ChangedItem.Value) ) 
        { 
            // the entered value is wrong - show error message 
            e.ChangedItem.PropertyDescriptor.SetValue( propertyGrid.SelectedObject, e.OldValue); 
            MessageBox.Show("Wrong Data", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
        } 
    }


    private static bool IsValid( int inputData) 
    { 
      // logic here
    } 

我希望这会帮助你解决问题!

I hope this will help you to solve the problem!