Let's say I got few radiobuttons and some custom object as datasource.
As example
public enum SomeModeType
{
firstMode = 10,
secondMode = 20,
thirdMode = 30
}
public class MyCustomObject:INotifyPropertyChanged
{
private SomeModeType _mode;
public SomeModeType Mode
{
set { _mode = value; }
get { return _mode; }
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
How to bind this object property (if its possible) to 3 different radiobuttons with something like:
If radiobuttonOne
checked - object property mode
sets to firstMode
If radiobuttonTwo
checked - object property mode
sets to secondMode
If radiobuttonThree
checked - object property mode
sets to thirdMode
etc etc
Or its better to use events for this?
P.S.
I know how to use events but its overwhelmed to create event by event like rb1chnaged
, rb2changed
, ..., rb100changed
, isnt it?
P.P.S.
MerryXmas!
For each value of the enum, you need to create a
RadioButton
and bind itsChecked
value toMode
property of data source. Then you need to useFormat
andParse
event ofBinding
to convertMode
value to suitable value forChecked
property and vise versa.Example - RadioButton List using FlowLayoutPanel
For example put a
FlowLayoutPanel
control on your form and then inLoad
event ofForm
write following code. The code will addRadioButton
controls to the flow layout panel dynamically and performs data-binding:In above example,
dataSource
can be aMyCustomObject
or aBindingList<MyCustomObject>
or aBindingSource
which contains aList<MyCustomObject>
in itsDataSource
.Another alternative - RadioButton List using Owner-draw ListBox
As another option you can use an owner-draw
ListBox
and renderRadioButton
for items. This way, you can bindSelectedValue
ofListBox
toMode
property of your object. ThedataSourcs
in following code can be like above example. Put aListBox
on form and write following code inLoad
event of form:Screenshot
You can see both solutions in following image:
Note
After answering this question, I created and shared a
RadioButtonList
control in this post: WinForms RadioButtonList doesn't exist.It has data-binding support and you can use this control like a
ListBox
. To do so, it's enough to bind it to the property of your model, and then set the data-source of the control simply this way: