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?
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;
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.