Home > Back-end >  Cannot implicitly convert type 'bool' to System.Windows.Forms.RadioButton
Cannot implicitly convert type 'bool' to System.Windows.Forms.RadioButton

Time:01-08

public partial class Form2 : Form {

 public bool male {get; set;}

{
 InitializeComponent();
} 
 private void Form2_Load(object sender, EventArgs e)
    {
        maleGender_rb1 = male;
    }

}

I want to display the radio buttton result from form1 to form2 using also radio buttons

CodePudding user response:

The best solution is to setup an event in the child form and for the RadioButton controls subscribe to CheckedChanged. The CheckedChange event determines which RadioButton was checked and sends notification to any listeners.

Child form:

namespace PassStringFromChildToParentForm
{
    public partial class ChildForm : Form
    {
        public delegate void OnPassData(bool isMale);
        public event OnPassData PassData;

        public ChildForm()
        {
            InitializeComponent();

            MaleRadioButton.Checked = true;
            MaleRadioButton.CheckedChanged  = RadioButton_CheckedChanged;
            FemaleRadioButton.CheckedChanged  = RadioButton_CheckedChanged;
        }

        private void RadioButton_CheckedChanged(object sender, EventArgs e)
        {
            var radioButton = (RadioButton)sender;
            if (radioButton.Checked)
            {
                PassData?.Invoke(radioButton == MaleRadioButton);
            }

        }
    }
}

Main Form:

Here we subscribe to the child form event and determine which RadioButton to check based on the bool value passed.

namespace PassStringFromChildToParentForm
{
    public partial class MainForm : Form
    {

        public MainForm()
        {
            InitializeComponent();
        }

        private void ShowChildForm_Click(object sender, EventArgs e)
        {
            ChildForm childForm = new ChildForm();
            childForm.PassData  = ChildForm_PassData; ;
            childForm.Show(this);
            
        }
        private void ChildForm_PassData(bool isMale)
        {
            if (isMale)
            {
                MaleRadioButton.Checked = true;
            }
            else
            {
                FemaleRadioButton.Checked = true;
            }
        }
    }
}

CodePudding user response:

You can't convert bool to RadioButton. I think you need to use Checked property of radio button to pass boolean value to it.

For example:

maleGender_rb1.Checked = true;// or false
  •  Tags:  
  • c#
  • Related