Reputation: 143
I have a validation method with 5 validation elements to it, 4 of which work as intended but 1 does not, question is why not?
The issue I have is with Validating "CompetitionCourse". I want the IsValid to be true only if the combobox cbCourseRound1 is not blank. At the moment this is validating regardless of this combobox being blank or populated. All other validations are working,
private bool Validate(Competition compSetup)
{
string CompetitionName = compSetup._CompetitionName;
int CompetitionFormat = compSetup._CompetitionFormatId;
string CompetitionGender = cbGenderOfCompetiton.Text;
string CompetitionMarker = cbMarker.Text;
string CompetitionCourse = cbCourseRound1.Text;
if (!CompetitionName.Equals(string.Empty) && !CompetitionGender.Equals("Mixed") && CompetitionFormat.Equals(1) && !CompetitionCourse.Equals(string.Empty) &&
((CompetitionGender.Equals("Female") && CompetitionMarker.Equals("Red")) || (!CompetitionGender.Equals("Female") && !CompetitionMarker.Equals("Red"))))
{
IsValid = true;
}
else
{
IsValid = false;
}
return IsValid;
}
Upvotes: 0
Views: 235
Reputation: 7008
May be you should try to trim the white space around the text box. For example, txtName.Trim();
Upvotes: 0
Reputation: 22794
Instead of using !Equals, use IsNullOrWhitespace, or IsNullOrEmpty. It works better.
Upvotes: 0
Reputation: 460138
Your code is diffficult to read, i'll try to simplify it:
private bool Validate(Competition compSetup)
{
bool isValid = cbGenderOfCompetiton.Text != "Female" && cbMarker.Text == "Red";
if (!isValid)
{
isValid = !string.IsNullOrEmpty(compSetup._CompetitionName);
if (isValid)
isValid = compSetup._CompetitionFormatId.Text == "Female";// this is redundant: cbGenderOfCompetiton.Text != "Mixed";
if (isValid)
isValid = CompetitionFormat == 1;
if (isValid)
isValid = cbCourseRound1.SelectedIndex != -1;
if (isValid)
isValid = cbMarker.Text == "Red";
}
return isValid;
}
Note that i've used the SelectedIndex
instead of Combobox.Text
because it's less error-prone.
Upvotes: 0
Reputation: 5265
depends on what's in CompetitionCourse
. You'll have to check that yourself by debugging your code.
You'd be better off making explicitly sure that CompetitionCourse
contains null
if the ComboBox text field is blank (because I suspect it contains ""):
CompetitionCourse = (string.IsNullOrEmpty(cbCourseRound1.Text)) ? null : cbCourseRound1.Text;
Upvotes: 1
Reputation: 39013
First of all, using .Equals
for strings is very Java. C# has operator overloading which looks a lot nicer:
if(CompetitionName!="" && CompetitionGender!="Mixed" ...)
As for the test itself, you'll need to set a break point and see what `CompetitionCourse has. My guess is it's not an empty string, but rather has some spaces in it. Try using
...!CompetitionCourse.Trim()!=""
Upvotes: 0