It's pretty simple: indentation does not control execution flow.
When you write code like:
if (txtaccount1.Text == "")
label17.Text = "<<";
label31.Text = "All Fields are Required";
The condition is evaluated and if true, the
next statement is executed.
if it is not true, then
the next statement is not executed and execution passes directly to the statement after it.
Unfortunatly for you,
label17.Text = "<<";
is the next statement, so
label31.Text = "All Fields are Required";
will
always be executed, regardless of the if condition being true or false.
If you want to execute more than one statement as a result of the if condition, you must make them a statement block, using curly braces:
if (txtaccount1.Text == "")
{
label17.Text = "<<";
label31.Text = "All Fields are Required";
}
"i want to apply form validations. if any field is empty, "All fields are required" such msg must show and "<<" must show on such text box, which is not filled. when it is filled msg ""All fields are required" and sign "<<" on empty text box must vanish..."
OK. That's a fairly normal requirement. The way I would do it may seem complex, but trust me, I've been doing this a long time...:laugh:
Firstly, change the names of your labels - don't use the VS defaults for this as it make code harder to read, and encourages bugs to breed! :laugh:
Instead of "label31" call it "labFieldRequired" or similar.
Instead of "label17" call it "labRequiredAccountNo" or similar.
It's difficult to read numerics and tie them to what is going on, so it makes it easier to get something wrong without noticing.
Second, why change the text of a label to indicate the problem? Why not fix the text, and change the Visible property instead? That way, you can see the labels on your form when you are designing them, and ensure that they line up well and look tidy.
Third, why set the overall result so many times? Just have a bool called "validationFailed", preset it to false, and set it to true each time you get a failure.
Then you just check it in the end, and set the overall result the once.
Fourth, instead of having individual if statement, why not use a method?
private bool Validate(bool condition, Label indicator)
{
indicator.Visible = !condition;
return condition;
}
Then your code becomes easier to read:
validationFailed |= Validate(!string.IsNullOrWhiteSpace(txtaccount1.Text), labRequiredAccountNo) ;
validationFailed |= Validate(!string.IsNullOrWhiteSpace(txtaccounttitle.Text), labRequiredAccountTitle);
(Note that I'm not checking against an empty string - the IsNullOrWhiteSpace method checks for nulls, empty strings, and spaces to ensure that the data is really present!)
Using "|=" here means that if any one or more validation fails, it will always leave
validationFailed
as true.