-2

So I'm building my first application and I want to make it so the person using the app cannot put text in any of the text boxes. Also I'd like to put some built in barriers so the program doesn't crash when they put nothing in the TextBox's.

Please help! Much appreciated!

Below is a picture.

What my application currently looks like.

Nelsencaleb
  • 23
  • 1
  • 7
  • Ugh. Use Label instead. – Hans Passant Jan 14 '16 at 00:07
  • @HansPassant he wants them to input numbers but not text labels wont work. – ivan Jan 14 '16 at 00:08
  • Can you be more specific as to why please. I am using two label's currently to give the final answers next to the tags "MPG" and "GPM". How would the user enter a number using a label is what I'm confused about as to your reply. – Nelsencaleb Jan 14 '16 at 00:09

1 Answers1

0

You should put a handler on the TextChanged event and parse the data as it is entered.

textbox1.TextChanged += ValidateInput;
textbox2.TextChanged += ValidateInput;
textbox3.TextChanged += ValidateInput;

...

private void ValidateInput(object sender, EventArgs args)
{ 
    bool valid = true;

    foreach(var textbox in new [] { textBox1, textBox2, textBox3})
    { 
        double value;
        if (!double.TryParse(textbox.Text, out value))
        { 
            textBox.Color = Color.Red;
            valid = false;
        }
        else
            textBox.Color = Color.Black;
    }

    buttonCalculate.Enabled = valid;
}
Jens Meinecke
  • 2,834
  • 16
  • 20
  • Sorry I'm still new to this. Could you explain what I replace the "ValidateInput;" with? I understand the textbox1,2,3 as examples but what should I be putting in place of the validateinput? – Nelsencaleb Jan 14 '16 at 00:22
  • @Nelsencaleb You wouldn't replace `ValidateInput`. It's a standard event handler. You could name it whatever you wish, however, like `NumericOnlyTextBox_TextChanged`, etc. – Mike Guthrie Jan 14 '16 at 01:27