Reputation: 225
I have a textbox that gets the gender value from database. Based on the textchanged event, the radiobuttons respond accordingly.
private void txtInvisibleGender_TextChanged(object sender, EventArgs e)
{
if (txtInvisibleGender.Text == "Female")
rbFemale.Checked = true;
else
rbMale.Checked = true;
}
The problem is that when the data in textbox is Female, then why is the Male radiobutton being checked? It doesn't check based on the data from the textbox. How do I make this work?
Upvotes: 2
Views: 1238
Reputation: 32671
You should user string.Compare instead of ==.
it means that your textbox doesn't have this value, atleast not in the same casing. Try this
private void txtInvisibleGender_TextChanged(object sender, EventArgs e)
{
if(string.Compare(txtInvisibleGender.Text.Trim(), "Female", StringComparison.OrdinalIgnoreCase) == 0)
rbFemale.Checked = true;
else
rbMale.Checked = true;
}
Upvotes: 3
Reputation: 12956
Your false branch
is always excecuting as your condition is never true
.
if (txtInvisibleGender.Text == "Female")
rbFemale.Checked = true;
else
rbMale.Checked = true; // we are reaching here.
I suggest changing it to
if (txtInvisibleGender.Text.Trim().ToLower().Contains("female"))
rbFemale.Checked = true;
else
rbMale.Checked = true;
It's worth noting that the if-else
will check male under all circumstances where txtInvisibleGender
does not contain "female"
. So typing "foobar"
will check male.
I would change it to:
// "female" contains "male" so Contains() cannot be used!
if (txtInvisibleGender.Text.Trim().ToLower().Equals("female"))
rbFemale.Checked = true;
if (txtInvisibleGender.Text.Trim().ToLower().Equals("male"))
rbMale.Checked = true;
then if it's anything other than "male"
or "female"
it doesn't check anything.
Upvotes: 2