I want to use one command which will contain two "textboxes.Text" in one "If". I mean when I did this command :
If (textBox1.Text == ("admin")) + (textBox2.Text == ("admin)) or this If (textBox1.Text == ("admin) , textBox2.Text == admin)) it isn't right.
The main code is:
private void Label_Click(object sender, EventArgs e)
{
if (textBox2.Text == ("admin")) + (textBox1.Text == ("admin"))
{
Label.Text = "right";
}
else
{
Label.Text = "wrong";
errorProvider1.SetError(errorprovider, "Wrong Username or Password");
}
Namely the thing I wanted to do is if one of two textboxes is wrong the label will show that the password or the username is wrong ... any ideas ?
The syntax for an if statement is:
if (condition) body
Your current code is:
if (textBox2.Text == ("admin")) + (textBox1.Text == ("admin"))
... which is treating textBox2.Text == ("admin") as the condition, and then trying to use + (textBox1.Text == ("admin")) as the body, which isn't valid. The problems are:
You're closing the condition too early
You're using the wrong operator for "and"
Additionally, you're putting parentheses around string literals for no obvious reason, reducing readability. So what you really want is:
if (textBox2.Text == "admin" && textBox1.Text == "admin")
Note that other answers have suggested using || instead of && - that would be an OR condition, which would show a result of "Right" if either of the textboxes had a value of admin. I suspect that's not what you want.
if (textBox1.Text == "admin" && textBox2.Text == "admin")
Label.Text = "right";
else
Label.Text = "wrong";
&& is the boolean AND operator. || is the boolean OR operator.
Check the MSDN page on C# Operators.
You're looking for || (conditional or) or && (conditional and).
The other name for conditional operators is "short-circuiting", because they only evaluate the second condition if they need to. In other words, with a && b, when a is false, the entire expression must be false, so the expression b is not evaluated. This is significant when b has side effects, or when a implies whether it is safe to evaluate b. Examples:
if (MethodA() && MethodB()) //...
Here, MethodB is called only when MethodA returns true.
if (o != null && o.Equals(p)) //...
This is safe (and common), because it saves us from the NullReferenceException when o is null.
You can also use the non-short-circuiting versions of these operators (| and &) with boolean expressions, but this is so rare that most programmers will read it, at first glance, as a mistake; it's better to be more explicit if you want the code always to evaluate both expressions.
if(textBox2.Text == "admin" && textBox1.Text == "admin")
{
//both admin
}
private void Label_Click(object sender, EventArgs e)
{
if ((textBox2.Text == "admin") || (textBox1.Text == "admin"))
{
Label.Text = "right";
}
else
{
Label.Text = "wrong";
errorProvider1.SetError(errorprovider, "Wrong Username or Password");
}
}
You need to use the "and" operator which is "&&" in C#.
if (textBox1.Text == ("admin")) && (textBox2.Text == ("admin))
Your expression is incorrect. The correct syntax is
if (A && B) { ... }
So in your case it should be
if(textBox1.Text.Equals("admin") && textBox2.Text.Equals("admin")) { ... }
You may want to read up a bit on Boolean algebra if this logic is confusing you.
Note the other changes we've all suggested as well - you had extra brackets and should be using Equals() for string comparison as well.
Seems like you need a simple or? Use the double vertical pipe ||
private void Label_Click(object sender, EventArgs e)
{
if (textBox2.Text == ("admin") || textBox1.Text == ("admin"))
{
Label.Text = "right";
}
else
{
Label.Text = "wrong";
errorProvider1.SetError(errorprovider, "Wrong Username or Password");
}
}
Related
I'm trying to add some bulletproofing in a DataGridView edit.
Columns 0, 1, 2, 3, 4 must have values to comply with datatable primary keys as well as SQL table constraints.
If any of the columns are blank I get either an internal exception on datatable primary keys or a SQL Exception on non nullable columns.
In the LeaveRow event, if any column values are null I'm calling CancelUpdate(). The problem is when CancelUpdate() executes, it is passing control to the top of the event and starting over.
Is this the correct behavior of CancelUpdate()?
Given my stated goal, is there another way I can accomplish?
.
private void dgvVX130_LeaveRow(object sender, DataGridViewCellEventArgs e)
{
bool z = true; // <======= CancelUpdate() passes execution to here
switch (dgvVX130.CurrentCell.ColumnIndex.ToString())
{
case "0":
if (dgvVX130.IsCurrentRowDirty &&
(dgvVX130.CurrentRow.Cells[1].Value.ToString() == "" ||
dgvVX130.CurrentRow.Cells[2].Value.ToString() == "" ||
dgvVX130.CurrentRow.Cells[3].Value.ToString() == ""))
{
z = false;
dgvVX130.CancelEdit(); // <=== Passes execution to top of event
MessageBox.Show("You must have Database, Schema, and TableName " +
"defined before leaving row"); // <===== Doesn't get executed
}
break;
case "1":
// Additional code is irrelevant
break;
}
}
Taking LarsTech suggestion I explored and used the RowValidating event. Was as simple as setting the CancelEventArgs.Cancel property to true. ( e.Cancel = True; )
private void dgvVX130_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
switch (dgvVX130.CurrentCell.ColumnIndex.ToString())
{
case "0":
if (dgvVX130.IsCurrentRowDirty && (dgvVX130.CurrentRow.Cells[1].Value.ToString() == ""
|| dgvVX130.CurrentRow.Cells[2].Value.ToString() == ""
|| dgvVX130.CurrentRow.Cells[3].Value.ToString() == ""))
{
e.Cancel = true;
MessageBox.Show("You must have Database, Schema, and TableName defined before leaving row");
}
break;
case "1":
if (dgvVX130.IsCurrentRowDirty && (dgvVX130.CurrentRow.Cells[0].Value.ToString() == ""
|| dgvVX130.CurrentRow.Cells[2].Value.ToString() == ""
|| dgvVX130.CurrentRow.Cells[3].Value.ToString() == ""))
{
e.Cancel = true;
MessageBox.Show("You must have Database, Schema, and TableName defined before leaving row");
}
break;
making a rock paper scissors game in C# for college.
I want to show message box when the player enters an invalid command (not rock, paper or scissors) . I tryed this but cant get it to work..
//if player enters wrong command they will
//this feedback
if (textBoxAttack.Text != "rock" || textBoxAttack.Text != "rock" || textBoxAttack.Text != "paper" || textBoxAttack.Text != "Paper" || textBoxAttack.Text != "scissors" || textBoxAttack.Text != "Scissors")
{
MessageBox.Show("Not a valid attack"
+ "\nPlease Enter one of the Following:"
+ "\nrock"
+ "\npaper"
+ "\nscissors");
textBoxAttack.Text = "";
}
It works if i just type in one command (eg: if (textBoxAttack.Text != "rock") )
any pointers?
Thanks.
You need && instead of ||.
However, i would prefer this concise and readable approach:
string[] allowed = { "rock", "paper", "scissors" };
if (!allowed.Contains(textBoxAttack.Text, StringComparer.CurrentCultureIgnoreCase))
{
string msg = string.Format("Not a valid attack{0}Please Enter one of the Following:{0}{1}"
, Environment.NewLine, string.Join(Environment.NewLine, allowed));
MessageBox.Show(msg);
textBoxAttack.Text = "";
}
Your boolean logic is wrong, because it will always not equal to one of the values, and thus will always be true. Change || to &&, and it should work.
Use an array, it makes your work easier.Also you can use ToLower method to make a case-insensitive check.
var values = new [] { "rock", "paper", "scissors" };
if(!values.Contains(textBoxAttack.Text.ToLower())
{
// invalid value
}
string text = textBoxAttack.Text.ToLowerInvariant();
if (text.Text != "rock" && text.Text != "paper" && text.Text != "scissors")
{
...
}
Use a dropdownlist/radiobuttons instead.
if (textBoxAttack.Text == "rock" || textBoxAttack.Text == "Paper" || textBoxAttack.Text == "Scissors")
{
//..Do What do you want
}
else
{
MessageBox.Show("Not a valid attack"
+ "\nPlease Enter one of the Following:"
+ "\nrock"
+ "\npaper"
+ "\nscissors");
textBoxAttack.Text = "";
}
Use Combo Box or 3 Buttons for this kind of problem.
Try to do the same but for example adding ToLower() at the end of each text attribute. This way you will only need to check 3 (rock, paper or scissors) becauuse the iput will be lower case ;)
And for the messageBox try something like this:
string[] message = { "Not a valid attack", "Please Enter one of the Following:", "rock", "paper", "scissors" };
if (textBoxAttack.Text.ToLower() != "rock" && textBoxAttack.Text.ToLower() != "paper" && textBoxAttack.Text.ToLower() != "scissors")
{
MessageBox.Show(string.Join("\n", message));
textBoxAttack.Text = "";
}
When trying a regular expression for no characters my winforms EnterValue is still being triggered after the if statement, how can I stop it from going any further after the trigger?
private void EnterValue_Click(object sender, EventArgs e)
{
if (textBox1.Text != string.Empty && !Regex.IsMatch(textBox1.Text, #"^[0-9]+$"))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
}
//convert input to double
listDouble.Add(Convert.ToDouble(textBox1.Text)); // this line still throws exception
textBox1.Clear();
//clear existing items
listBox1.Items.Clear();
// clear any existing list items
for (int i = 0; i < listDouble.Count; i++)
{
listBox1.Items.Add(listDouble[i]);
}
//for each value added, add this to our list
}
Return from the method:
if (textBox1.Text != string.Empty && !Regex.IsMatch(textBox1.Text, #"^[0-9]+$"))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
return; // nothing after this will execute
}
This will execute only if the if predicate is true, and the method will return as soon as the return; statement has been hit, without any of the other code being run.
First option is to use return:
if (textBox1.Text != string.Empty && !Regex.IsMatch(textBox1.Text, #"^[0-9]+$"))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
return; // exit method
}
Second option is to use else:
if (textBox1.Text != string.Empty && !Regex.IsMatch(textBox1.Text, #"^[0-9]+$"))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
}
else
{
// your statements
}
Use Decimal.TryParse. And use return after checking condition to exit from current method:
The return statement terminates execution of the method in which it appears and returns control to the calling method.
Decimal dec;
if (!Decimal.TryParse(textBox1.Text, out dec))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
return;
}
I remember using some attribute on the getter/setter that would limit the input to a certain datatype, length etc. IE [Attribute something something].
Any ideas?
Thanks
Did you mean the ValidateInput attribute available in System.Web.Mvc?
Also, you could probably use a MaskedTextBox if you're doing WinForms.
One way to do it (if you want to keep using a standard text box) would be to make an event for the text changed event of the text box, and in that, read the text to make sure that it contains only numbers (and an optional period in the case of a double)
Winforms? Have you considered using masked Textbox control?
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx
Winforms? Why not use a NumericUpDown?
http://msdn.microsoft.com/en-us/library/57dy4d56.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.numericupdown.aspx
If you need scientific notation you can do :
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
TextBox tBox = (TextBox)sender;
if (!((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9)
|| (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)
|| (e.KeyCode == Keys.Decimal && !(tBox.Text.Contains('.'))
&& !(tBox.Text.Length == 0)
&& !((tBox.Text.Length == 1)
&& (tBox.Text.Contains('-') || tBox.Text.Contains('+'))))
|| (e.KeyCode == Keys.OemPeriod && !(tBox.Text.Contains('.'))
&& !(tBox.Text.Length == 0)
&& !((tBox.Text.Length == 1)
&& (tBox.Text.Contains('-') || tBox.Text.Contains('+'))))
|| (e.KeyCode == Keys.Subtract && ((tBox.Text.Length == 0) ||
tBox.Text.EndsWith("e") || tBox.Text.EndsWith("E")))
|| (e.KeyCode == Keys.OemMinus && ((tBox.Text.Length == 0) ||
tBox.Text.EndsWith("e") || tBox.Text.EndsWith("E")))
|| (e.KeyCode == Keys.Add && ((tBox.Text.Length == 0) ||
tBox.Text.EndsWith("e") || tBox.Text.EndsWith("E")))
|| (e.KeyCode == Keys.Oemplus && ((tBox.Text.Length == 0) ||
tBox.Text.EndsWith("e") || tBox.Text.EndsWith("E")))
|| e.KeyCode == Keys.Delete
|| e.KeyCode == Keys.Back
|| e.KeyCode == Keys.Left
|| e.KeyCode == Keys.Right
|| (e.KeyCode == Keys.E) && !(tBox.Text.Contains('e')) &&
(tBox.Text.Contains('.') && !tBox.Text.EndsWith("."))))
{
e.SuppressKeyPress = true;
}
}
This will deny input of any pattern which is not consistent with a numeric value. Minus signs are only allowed at the beginning of the string (to indicate a negative number) and after an e or E to indicate a negative exponent. Plus signs follow the same rule as minus. Only one decimal point is allowed and it must follow at least one number. Only one e or E is allowed and it must follow a decimal point and at least one number after the decimal point.
You could also allow things like the Help, Tab, etc, keys if it would interfere with other aspects of your program function.
Note that this does not prevent incomplete numbers (ie: 1.37E- or -13. from being entered so you would probably want to check the string in any case. This at least denies any immediately invalid entries.
You might do something like (in the same handler, before the other logic):
if (e.KeyCode == Keys.Enter)
{
textBox1_Validating(sender, new CancelEventArgs());
return;
}
The above only gives the enter key the normal 'feel' for input (force validation). Leaving the textbox (going out of focus) will also trigger validation where you might do something like :
private void textBox1_Validating(object sender, CancelEventArgs e)
{
TextBox tBox = (TextBox)sender;
double tstDbl;
if (!double.TryParse(tBox.Text, out tstDbl))
{
//handle bad input
}
else
{
//double value OK
doSomething(tstDbl);
}
}
I have a form in which there are many textBoxes from which three textboxes are required to fill in order to submit the form. I dont want to use each If block for each text box. Is there any way to use a single if statement for all the three text boxes? I am using the following code:
if (textBox1.Text != "" || textBox2.Text != "" || textBox4.Text != "")
{
// Code
}
else
{
MessageBox.Show("Fill required fields");
}
but this code works even a single text fox is filled and the rest of the required text boxes are empty.
if (textBox1.Text != "" && textBox2.Text != "" && textBox4.Text != "")
{
// Code
}
else
{
MessageBox.Show("Fill required fields");
}
You want all conditions to pass. This fits the semantics of the logical AND operator &&.
If you have tons of textboxes, I would tend to keep them in a list:
var boxes = new List<TextBox>{
textBox1,
textBox2,
textBox3,
//...
};
if (boxes.Any(tb => string.IsNullOrEmpty(tb.Text)))
{
MessageBox.Show("Fill required fields");
}
else
{
// Code
}
I also tend to prefer to keep the exception in the if part, returning or throwing an error and ommit an else part, since that is just normal code flow. This keeps the code you expect to run as far to the left as possible.
You should change || to &&
You created a collection of or statements, so only one needs to be true in order to continue. Instead you need to and them:
if (textBox1.Text != "" && textBox2.Text != "" && textBox4.Text != "")
You may define a method to test empty strings.
public class Test
{
public static bool IsEmpty(params string []args)
{
if (args.Length == 0) return true ;
return args.Any(p => string.IsNullOrEmpty(p));
}
}
To test strings,
if(!Test.IsEmpty(TextBox1.Text,TextBox2.Text,TextBox3.Text))
{
//valid
}
You use OR (||) and should use AND (&&) instead. You want ALL three textboxes to be non-empty strings. Check out the following code:
if (textBox1.Text != String.Empty && textBox2.Text != String.Empty && textBox4.Text != String.Empty)
{
// Code
}
else
{
MessageBox.Show("Fill required fields");
}
You can also make a collection of TextBoxes and loop through them to check for non-empty Strings. Something like this:
List<TextBox> _lstTextBoxes = new List<TextBox>();
_lstTextBoxes.Add(textBox1);
_lstTextBoxes.Add(textBox2);
_lstTextBoxes.Add(textBox3);
Boolean checkFailed = false;
foreach(TextBox tb in _lstTextBoxes)
if(tb.Text == String.Empty)
checkFailed = true;
if(checkFailed)
MessageBox.Show("Fill required fields");
else
//code
This way you have a more generic approach to which you can easily add or remove certain textboxes.
Instead of using OR (||) use AND (&) in your condition.
Suggestion
Use Trim function from string to remove any white spaces from textbox (if required)
Instead of comparing like textBox1.Text != "" do String.IsNullOrEmpty(textBox1.Text) == false
Assuming you have 4 textboxes in total, below code will work
if ((textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "") || (textBox1.Text != "" && textBox2.Text != "" && textBox4.Text != "") ||
(textBox1.Text != "" && textBox3.Text != "" && textBox4.Text != "") || (textBox2.Text != "" && textBox3.Text != "" && textBox4.Text != "")
)
{
// Code
}
else
{
MessageBox.Show("Fill required fields");
}