| View previous topic :: View next topic |
| Author |
Message |
zaczac Master Cheater
Reputation: 0
Joined: 01 May 2007 Posts: 266 Location: Ontario, Canada
|
Posted: Tue Nov 15, 2011 6:34 pm Post subject: c# methods |
|
|
I am just starting to learn methods and need to create one that will check to see if a user entered a valid entry in a text box. The valid entry's are
"+" "-" "/" "*" without quotes.
Basically coding a calculator and one of the text boxes requires the user to enter one of those operators, I need to check to make sure one is entered.
If anyone could give me some ideas or help out I would appreciate it.
Thanks in advanced!
|
|
| Back to top |
|
 |
Stylo Grandmaster Cheater Supreme
Reputation: 3
Joined: 16 May 2007 Posts: 1073 Location: Israel
|
Posted: Wed Nov 16, 2011 3:54 am Post subject: |
|
|
Limit the number of characters allowed inside the textbox to only 1 character,
And check whether the entered character is one of those operators.
_________________
Stylo |
|
| Back to top |
|
 |
zaczac Master Cheater
Reputation: 0
Joined: 01 May 2007 Posts: 266 Location: Ontario, Canada
|
Posted: Wed Nov 16, 2011 9:22 am Post subject: |
|
|
| I know that much, just not sure what to use to check if they entered one..
|
|
| Back to top |
|
 |
Stylo Grandmaster Cheater Supreme
Reputation: 3
Joined: 16 May 2007 Posts: 1073 Location: Israel
|
Posted: Wed Nov 16, 2011 11:02 am Post subject: |
|
|
I guess it'd look something like:
| Code: |
private void button1_Click( object sender, EventArgs e ) {
string op = txtOperator.Text;
switch( op ) {
case "+":
// code
break;
case "-":
// code
break;
case "*":
// code
break;
case "/":
// code
break;
}
}
|
_________________
Stylo |
|
| Back to top |
|
 |
zaczac Master Cheater
Reputation: 0
Joined: 01 May 2007 Posts: 266 Location: Ontario, Canada
|
Posted: Wed Nov 16, 2011 1:05 pm Post subject: |
|
|
Thanks stylo, I actually found another way to do this as well, would this be a "correct" way of doing it?
| Code: | public bool IsOperator(TextBox textBox, string name)
{
bool valid = true;
if (textBox.Text != "+" && textBox.Text != "-" && textBox.Text != "/" && textBox.Text != "*")
{
MessageBox.Show(name + "Please enter a valid operator.");
textBox.Focus();
valid = false;
}
return valid;
} |
|
|
| Back to top |
|
 |
Unbr0ken Advanced Cheater
Reputation: 2
Joined: 10 Aug 2011 Posts: 67
|
Posted: Thu Nov 17, 2011 10:34 pm Post subject: |
|
|
| Why don't use the KeyDown Event?
|
|
| Back to top |
|
 |
FLiNG Newbie cheater
Reputation: 0
Joined: 09 Apr 2011 Posts: 19
|
Posted: Fri Nov 18, 2011 12:52 am Post subject: |
|
|
There are many ways of doing this, I think it is easier to use Key Events. The following code uses Keypress Event to avoid any characters other than +-*/ go into the textbox.
| Code: | private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = "+-*/".IndexOf(char.ToUpper(e.KeyChar)) < 0;
} |
|
|
| Back to top |
|
 |
|