WinForm binding radio button
Asked Answered
N

3

21

I use VS2010 and then drag and drop Member datagridview to design view. After that I drag and drop name member textfield to design view and then try to edit and save. It's work properly.

And then I drag and drop sex radio button to design view. But binding it does't work.

How can I binding in this situation?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Test7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void memberBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.memberBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.dbDataSet);

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'dbDataSet.Member' table. You can move, or remove it, as needed.
            this.memberTableAdapter.Fill(this.dbDataSet.Member);
            // TODO: This line of code loads data into the 'dbDataSet.Member' table. You can move, or remove it, as needed.
            this.memberTableAdapter.Fill(this.dbDataSet.Member);

        }


        private void memberBindingNavigatorSaveItem_Click_1(object sender, EventArgs e)
        {
            this.Validate();
            this.memberBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.dbDataSet);

        }
    }
}

enter image description here

Nan answered 18/1, 2012 at 6:53 Comment(3)
What's the difference between memberBindingNavigatorSaveItem_Click and memberBindingNavigatorSaveItem_Click_1 ? Am I missing something? +1 for taking the time to post code and screenshot though.Eurhythmy
There's no difference between those two events, you have created a new Click event when there's already a event exists.Chinatown
Are you grouping your radio buttons in a GroupBox and then using the CheckedChanged event? That should give you enough flexibility to pull this off, I would think.Eurhythmy
M
19

Here are two possible solutions.


Binding Format and Parse events

The Binding class has a built-in facility for on-the-fly transformations of bound data in the form of the Format and Parse events.

Here's how you would use those events with just the "Male" radiobutton. Create the binding in code, not in the designer:

// create binding between "Sex" property and RadioButton.Checked property
var maleBinding = new Binding("Checked", bindingSource1, "Sex");
// when Formatting (reading from datasource), return true for M, else false
maleBinding.Format += (s, args) => args.Value = ((string)args.Value) == "M";
// when Parsing (writing to datasource), return "M" for true, else "F"
maleBinding.Parse += (s, args) => args.Value = (bool)args.Value ? "M" : "F";
// add the binding
maleRb.DataBindings.Add(maleBinding);

// you don't need to bind the Female radiobutton, just make it do the opposite
// of Male by handling the CheckedChanged event on Male:
maleRb.CheckedChanged += (s, args) => femaleRb.Checked = !maleRb.Checked;

Computed Property

Another approach is to add a computed property to your datasource:

public bool IsMale
{ 
    get { return Sex == "M"; }
    set 
    {  
        if (value)
            Sex = "M";
        else
            Sex = "F";
    }
}

Now you can simply bind the Male radiobutton to this property on your datasource (just don't show this property in the grid).

And again you can hook up Female to Male like so:

maleRb.CheckedChanged += (s, args) => femaleRb.Checked = !maleRb.Checked;
Metallist answered 18/1, 2012 at 22:27 Comment(4)
I try solution#1 and if I set all records are female, it will no any radio button checked. [ i.imgur.com/zo2KF.jpg ]Nan
The other solution is just to make sure the initial state of the male radiobutton is Checked = true. That way when binding occurs, it will be changed to False, and that will trigger the female to be updated.Metallist
At Solution#2: Is there such a keyword property?Thew
@mmdemirbas: no there isn't, thanks for pointing that out. Sometimes my fingers are directly linked to my brain and my brain is thinking in the wrong language. Maybe that's Delphi syntax; I was a Delphi programmer many years ago.Metallist
S
2

While I realize this has already been answered, I thought I would provide an option that gives design time binding ability.

Make a new Custom RadioButton Object. This is done with the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MSLabExample
{
    class RadioButtonBind : RadioButton
    {
        private string _selectValue = string.Empty;
        public string SelectValue
        {
            get { return _selectValue; }
            set
            {
                if (value == Text) Checked = true;
                else Checked = false;
                _selectValue = value;
            }
        }

        public RadioButtonBind()
        {
            this.CheckedChanged += new EventHandler(RadioButtonBind_CheckedChanged);
            this.TextChanged += new EventHandler(RadioButtonBind_TextChanged);

        }
        void RadioButtonBind_TextChanged(object sender, EventArgs e)
        {
            if (Checked) _selectValue = Text;
        }

        void RadioButtonBind_CheckedChanged(object sender, EventArgs e)
        {
            if (Checked) _selectValue = Text;
        }
    }
}

The basic concept of the above control is to use a string value that can be bound and will check itself if the bound string value is equal to the radio button text.

By using the radio button text, it allows easy understanding of the proper checked value, and also allows the SelectValue to be updated by simply changing the radio button text. No extra code is needed when modifying the radio button.

Now you simply bind the SelectedValue property for all radio buttons in the same group to some string property.

Limitations:

  1. Two radio buttons in the same group cannot have the same text (but is this really a limitation?)
  2. At design time, the checked values of the radio buttons may not appear accurate (i.e. two radio button in the same group may appear to be checked). This should not occur at runtime however.

Note when creating a custom control, the project must be built before the custom object is available in the toolbox.

Sarad answered 28/8, 2012 at 7:31 Comment(0)
G
0

When making forms you can drag items from the "Data Sources" panel. In the data sources panel you can a class or table and all the children of it can be dragged to the form and will automatically generate a textbox or in this scenario a radio button with a data binding. In the database or class you will have to make a bit / bool for every option.

Group the radio buttons and add a radio button without a databinding to keep all bit / bools 0.

Set CausesValidation to False for all radio buttons.

When saving the changes loop through all radio buttons like:

((YourClass)myBindingSource.DataSource).property1 = radioButton1.Checked;
((YourClass)myBindingSource.DataSource).property2 = radioButton2.Checked;

I think this is a copy of How do I use databinding with Windows Forms radio buttons? And therefore, here is a copy of my answer there.

Gibbet answered 23/5, 2017 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.