C# radiobutton value (boolean) to another class

时间:2015-11-12 10:51:37

标签: c# radio-button boolean

I'm trying to have value selected by user in form of a radio button sent to another class which does the calculations.

in MainForm.cs I have this:

private bool ReadInputBMR()
    { bla bla bla...
        if (rbtnFemale.Checked)  ;
        { calCalc.SetGender(2); }
        if (rbtnMale.Checked) ;
        { calCalc.SetGender(1); }
     bla bla 
}

And in the class that does the calculation I have this: Class name is: CalorieCalculator.cs

        public void SetGender(int value)
    {
        if (value > 2) 
        { this.isFemale = false; }
       else if (value == 2)  
        { this.isFemale = true; }  

    }

    public bool GetGender()
    {
        if (isFemale == true)
        {
            return isFemale == true;
        }
        else if (isFemale == false)
        {
            return isFemale == false;
        }            
    }

    public double CalcBasMetabolicRateBMR()           
    {
        BMR = (10 * weight) + (6.25 * height) - (5 * age);
        BMRFemale = BMR - 161;
        BMRMale = BMR + 5;
        if (isFemale == true)
            return BMRFemale;
        else
            return BMRMale;
}

I'm pretty sure I messed up somewhere (or everywhere). The other values seem to be working it's just the values from the radio buttons that isn't working.

Thank you for your help

2 个答案:

答案 0 :(得分:1)

What might be the problem is that SetGender() is called with value 1 and the implementation does not do anything since it checks for >= 2 and == 2.

Btw, why not make the implementation easier (and equal) by changing:

public void SetGender(int value)
{
    if (value > 2) 
    { this.isFemale = false; }
   else if (value == 2)  
    { this.isFemale = true; }  
}

to

public void SetGender(int value)
{
    this.isFemale = (value == 2); 
    // Note: Since 1 is not handled this might be causing your problem
    // In your example when value == 1, nothing happens.
}

Change

public bool GetGender()
{
    if (isFemale == true)
    {
        return isFemale == true;
    }
    else if (isFemale == false)
    {
        return isFemale == false;
    }            
}    

to

public bool GetGender()
{
    return !isFemale;
}

Change

if (isFemale == true)
    return BMRFemale;
else
    return BMRMale;

to

return isFemale ? BMRFemale : BMRMale;

In general it is not a good idea to use values like 1, 2 etc. for enumeration types.

Better is to use:

public enum EGender { Unknown, Male, Female };

This will keep your code much clearer. If you do not need the Unknown value, you can use a boolean directly (like IsFemale ), without the necessity for the 1 and 2 value.

Also consider properties like public EGender Gender { get; set; } instead of separate Get and Set methods.

答案 1 :(得分:0)

Your Code should be like this

if (rbtnFemale.Checked==true)
{
    calCalc.SetGender(2);
}
else if (rbtnMale.Checked==true)
{
    calCalc.SetGender(1);
}