How do I disable a button when the value in the NumericUpDown control is greater than a certain number?

StackOverflow https://stackoverflow.com/questions/13276444

  •  27-11-2021
  •  | 
  •  

سؤال

The button only disables after I click on it. I want it to disable without any interaction as soon as the value in the NumericUpDown control is incremented above a specific point. I have goggled but found no answers, here is my code:

    private void mybtn_Click(object sender, EventArgs e)
    {            
        if (numericud.Value > myArray[r, c] || myArray[r, c] == 0)
            DisableButton(mybtn);            
        myArray[r, c] = CalcNewMax(myArray[r, c]);
        OpenNewForm();
    }

    private void DisableButton(Button selectedbtn)
    {
        selectedbtn.Enabled = false;
    }

Any help is much appreciated, thanks!

هل كانت مفيدة؟

المحلول 2

I think you are calling the method "mybtn_Click()" when the button gets clicked, not when the value of the numeric up-down changes. In the "Events" part of the properties of the button check out if the "MouseClick" event is set to call "mybtn_Click()".

Afterwards go to the "Events" part of the properties of the numeric up-down and set the "ValueChanged" event to call "mybtn_Click()". I also advise you to change the name of the method to a more suitable one before that.

And lastly, you don't need to make a whole new method for simply changing the Enabled value of the button: simply replace the line

DisableButton(mybtn);

with

mybtn.Enabled = false;

نصائح أخرى

Here's some code that works for a specific example.

I don't see any specific problems with your code, so if I were you, I'd put some breakpoints in to make sure that your condition is fulfilled, and that everything is proceeding as you think it is.

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            if (numericUpDown1.Value > 5)
                button1.Enabled = false;
        }
    }
}

As an additional note, Visual Studio will automatically generate the numericUpDown1_ValueChanged handler when you double-click on the UpDown control in the designer

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top