tags:

views:

250

answers:

2

I've got a form where I have two radio buttons and two interchangeable controls (made up of a ListView and a handful of buttons). Based on which radio button is selected I want to display the proper control to the user.

The way I'm doing this now is just loading both controls and setting up an OnRadioButtonSelectionChanged() method which gets called at form load (to set the initial state) and at any time the selection is changed. This method just sets the visible property on each control to the proper value.

This seems to work well enough, but I was curious as to if there was a better or more common way of doing it?

+3  A: 

Yep, that's pretty much how I do it. I would set the CheckedChanged event of both radio buttons to point at a single event handler and would place the following code to swap out the visible control.

private void OnRadioButtonCheckedChanged(object sender, EventArgs e)
{
    Control1.Visible = RadioButton1.Checked;
    Control2.Visible = RadioButton2.Checked;
}
Lloyd Cotten
+2  A: 

Well you could also use databinding... seems a bit more elegant to me. Suppose you have two radiobuttons "rbA" and "rbB" and two textboxes "txtA" and "txtB". And you want to have txtA visible only when rbA is checked and txtB visible only when rbB is checked. You could do it like so :

private void Form1_Load(object sender, EventArgs e)
{
    txtA.DataBindings.Add("Visible", rbA, "Checked");
    txtB.DataBindings.Add("Visible", rbB, "Checked");
}

However... I observed that using UserControls instead of TextBoxes breaks the functionality and I should go read on the net why..

LATER EDIT :

The databinding works two-ways! : If you programatically set (from somewhere else) the visibility of the txtA to false the rbA will become unchecked. That's the beauty of Databinding.

Andrei Rinea
Interesting, I hadn't come across databinding yet (I'm still fairly new to C# development). I'll have to check it out.
Lawrence Johnston