简体   繁体   中英

NumericUpDown ValueChanged preventDefault?

I want to create a form that allows the user to set a certain amount of points in five different fields (NumericUpDown). When that amount of points reaches 0, the user can't add any more. (I still want the user to be able to remove points, though.)

Here is my code so far:

private void calculateValue() {
  decimal tempValue = CMB_num_Aim.Value + CMB_num_Reflexes.Value + 
  CMB_num_Positioning.Value + CMB_num_Movement.Value + CMB_num_Teamwork.Value;
  controlValue = currentValue - tempValue;
  MyBox.CMB_tb_cv.Text = controlValue.ToString();
}

This Method (calculateValue) is calculates how many points the user have left (controlValue).

private void CMB_num_Aim_ValueChanged(object sender, EventArgs e) {
  calculateValue();
  if (controlValue < 0) {
     //Prevent Default here
     MessageBox.Show("You are out of points!");
  }
}

This method (CMB_num_Aim_ValueChanged) fires when the value of the NumericUpDown control has changed. I have one of these for each field, each doing the same thing.

The method fires as expected, but I can't prevent it from happening - the user can apply more points than they have. How can I prevent the user from applying more points?

(I thought about making a mouseUp method, but I don't know if the user will use the mouse or if he will type in the value using the keyboard.)

Replace

if (controlValue < 0) {

By

if (controlValue <= 0) {

Seems like you want to create a point distribution system between some skills - aim, movement, teamwork etc. You can do that easily by setting Maximum value of NumericUpDown control when you enter it. Subscribe all skill updown controls to the same event handler:

private void SkillNumericUpDown_Enter(object sender, EventArgs e)
{
   var skill = (NumericUpDown)sender;
   var availablePoints = 42;
   var maxSkillPoints = 20; // usually you cannot assign all points to one skill
   var unassignedPoints = availablePoints - SkillPointsAssigned;
   skill.Maximum = Math.Min(maxSkillPoints, unassignedPoints  + skill.Value);

   if (unassignedPoints == 0)
   {
       MessageBox.Show("You are out of points!");
       return;
   }

   if (skill.Value == maxSkillPoints)
   {
       MessageBox.Show("Skill maximized!");
       return;
   }
}

private decimal SkillPointsAssigned =>
    CMB_num_Aim.Value + 
    CMB_num_Reflexes.Value + 
    CMB_num_Positioning.Value + 
    CMB_num_Movement.Value + 
    CMB_num_Teamwork.Value;

Benefit - you will not be able to input illegal value neither by arrows nor manually.

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