views:

627

answers:

2

Hello,

I'm trying to bind an SQL table to radiobuttons in a windows form application. The buttons are grouped by groupboxes. I haven't yet find a way to bind them correctly to the datasource. I know some had managed to do this by creating a custom control but I wonder if there is a simpler way?

+1  A: 

I've used a dirty trick:

Create a hidden textbox. Bind it to the datasource, and leave the radio buttons unbound. Then program the textbox change event to set the radio buttons value and the radio button click events to set the text bot value.

Dirty, but it works.

tekBlues
WTF!?! :D
Daniel Brückner
Very clever! :)
G Berdal
That's pretty good...
lc
+3  A: 

Edit: This is probably a cleaner way to do it (untested, but should work).

You should actually bind directly (using a Binding) to the radiobuttons, but handle the Binding.Parse and Binding.Format events.

In the 'Format' event, set the Checked properties and in the Parse event, you'll save the value back based on which one is checked.


Original Idea: Without creating a custom control or subclassing, the simplest way is probably not to bind directly but to load and save the values yourself as an intermediary.

One way is:

  • Subscribe to the BindingSource.CurrentItemChanged event and set the radiobutton Checked properties accordingly.

  • Subscribe to the RadioButton.CheckedChanged events and set the underlying data source appropriately.

lc
This is a far better solution than mine!, you have to remember the name of those events of course, but it's elegant +1
tekBlues
Sounds good. Thanks! - I would give +1 but I have no credentials yet ;)
G Berdal
Sounds even better! Thanks very much.
G Berdal
No I do. :) so here you go +1. Thanks again.
G Berdal
I take it it worked then?
lc
Yes. After getting my head around it, it did. :) Thanks very much.
G Berdal