Determine If Changed Event Occurred from User Input Or Not

后端 未结 6 878
借酒劲吻你
借酒劲吻你 2021-01-18 00:38

In C#, the Changed event for a control (say, a numericupdown) gets fired whether the value was change directly by the user or if it was changed programatically as the result

6条回答
  •  青春惊慌失措
    2021-01-18 01:02

    I have solved this problem before. Let's take the NumericUpDown control as an illustrative example.

    First, create a new control (call it MyNumericUpDown) that inherits from the NumericUpDown. Create overrides for the UpButton, DownButton, and OnLostFocus methods. Also create a public method for setting the value of the control programmatically. Create an enum type called 'ValueChangedType' that has 4 different values called TextEdit, UpButton, DownButton, and Programmatic (or call them whatever you like). Also create a property called ChangedType of type ValueChangedType. Here is what the class looks like.

    public partial class MyNumericUpDown : NumericUpDown
    {
        public enum ValueChangedType
        {
            TextEdit,
            UpButton,
            DownButton,
            Programmatic
        }
        public ValueChangedType ChangedType = ValueChangedType.Programmatic;
        public MyNumericUpDown()
        {
            InitializeComponent();
        }
        public override void UpButton()
        {
            this.ChangedType = ValueChangedType.UpButton;
            base.UpButton();
        }
        public override void DownButton()
        {
            this.ChangedType = ValueChangedType.DownButton;
            base.DownButton();
        }
        protected override void OnLostFocus(EventArgs e)
        {
            this.ChangedType = ValueChangedType.TextEdit;
            base.OnLostFocus(e);
        }
        public void SetValue(decimal val)
        {
            this.ChangedType = ValueChangedType.Programmatic;
            this.Value = val;
        }
    }
    

    Now, in your form, create a MyNumericUpDown control (call it 'myNUD'). In the ValueChanged event handler for the control, you can get the value of the ChangedType property, and do something with it:

        private void myNUD_ValueChanged(object sender, EventArgs e)
        {
                MyNumericUpDown nud = sender as MyNumericUpDown;
                var myChangedType = nud.ChangedType;
                /* do something */
        }
    

提交回复
热议问题