Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitor keystrokes

I am a beginner in C# , and making a calculator . But i want to disable the "GO!" button when there's no number typed in textbox1 and once the user enters a number in it the "GO!" button becomes enabled again ... how to do this in C# ? i tried KeyDown and KeyPress event like this but never worked

private void Form1_Load(object sender, EventArgs e)
    {

            button15.Enabled = false;
         button16.Enabled = false;     

    }


 private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyEventArgs e)
    {

       if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
        {
            button15.Enabled = true;
            button16.Enabled = true;

        }
        else
        {
            button15.Enabled = false;
            button16.Enabled = false;
        }

    } 

so how to do this please ? thanks in advance .

like image 218
rafael Avatar asked Dec 29 '25 19:12

rafael


1 Answers

Your idea is pretty good but there is a better way. Just detect when the contents of the text box change. When the contents change, check to see whether the contents are empty or not empty. If the contents are empty then disable the button, otherwise enable it.

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.textchanged.aspx

Also, it would be a good idea for you to change the names of your controls to something other than the defaults. "button15" tells the reader of the code nothing, "goButton" does.

like image 91
Eric Lippert Avatar answered Jan 01 '26 08:01

Eric Lippert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!