开发者

Monitor keystrokes

开发者 https://www.devze.com 2022-12-22 15:33 出处:网络
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

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开发者_JS百科 this please ? thanks in advance .


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.


private void textBox1_TextChanged(object sender, EventArgs e)
{
      if(String.IsNullOrEmpty(textBox1.Text))
      {
            button15.Enabled = false;
            button16.Enabled = false;
      }
      else
      {
            button15.Enabled = true;
            button16.Enabled = true;
      }
}


You'll want to check if the text box value can actually be converted to a number. Checking for digits isn't good enough, you'll accept something bad like "4-" or reject something good like "1e3". And please use meaningful control names so you don't accidentally enable the wrong control. For example:

private void txtOperand_TextChanged(object sender, EventArgs e) {
  double value;
  btnGo.Enabled = double.TryParse(txtOperand.Text, out value);
}

This probably isn't quite good enough for your calculator, but demonstrates the approach.


How about using the TextChanged event, and then checking if the textbox is empty or has something in it and enabling or disabling the button accordingly?

Also, if you were using WPF, you could write a command for your GO button which would automagically handle activation and deactivation of the command (and any controls which subscribe to it). Your activation logic would be simply to check if there's text in the textbox.

0

精彩评论

暂无评论...
验证码 换一张
取 消