Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
if (sexch.Checked == true)
            {

                ch.Text = "male";
            }
           else  if (sexch.Checked == false)
            {
                ch.Text = "Female";

            }


I have this code when the checkbox ==true I want a label.text to change to male. The problem is that the program only read the else.

I am getting the sexch checkbox from a database and depending on the output(true=male, false=female) of the database I want to change the label.text.

What I have tried:

if (sexch.Checked == true)
            {

                ch.Text = "male";
            }
           else  if (sexch.Checked == false)
            {
                ch.Text = "Female";

            }



if (sexch.Checked == true)
            {

                ch.Text = "male";
            }
             if (sexch.Checked == false)
            {
                ch.Text = "Female";

            }
Posted
Updated 7-Jun-18 11:16am

Your problem is that you don't need the second if statement at all. If the checkbox is not true, it must be false.
C#
if (sexch.Checked == true)
{
    ch.Text = "Male";
}
else
{
    ch.Text = "Female";
}
 
Share this answer
 
Comments
Ahmed Taha 6-Jun-18 11:42am    
Still, I have the same problem.
The program does not go through the (if)part, it only sees the else part whether the checkbox is true or false.
Dave Kreskowiak 6-Jun-18 11:44am    
You're going to have to go through the code in the debugger to see what's happening. The code I posted will work and will only pick one path, either ch.Text is going to be "Male" or it's going to be "Female".

BUT! This will only work depending on the code around this code and the context in which it is executing. Since we can only work with exactly what you type into the question, we can't go any farther than this.

Learn to use the debugger and step through the code line-by-line and examine the variable contents. This is the only way you're going to figure this problem out.
Use CheckBox.CheckedChanged Event (System.Windows.Forms)[^]

Inside of it, use:
C#
ch.Text = sexch.Checked ? "Male" : "Female";


In case you want to change checkbox state based on database value:
C#
sexch.Checked = database_value;



For further details, please see: CheckBox.Checked Property (System.Windows.Forms)[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900