HotDog's Blog

Hotdog (Robert Verpalen) about C# and vb.net

vbCity Blogs moved to:
http://cs.vbcity.com/blogs
  Home :: Syndication  :: Login

OctNovember 2009Dec
SMTWTFS
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

Articles

Archives

Topics

CONTACT

Fun but useful linkies

General

VS 2005

Wolfenstein ET

Perhaps I've missed the option completely, but I didn't see a way to simply bind a group of radiobuttons to a datasource, hence this little control.

It is a very very simple control inherited from groupbox that keeps track of the radiobuttons added to it. After that, the SelectedIndex can be set to select a specific control. That's also the property of course that can be used for the databinding

Code Copy HideScrollFull
    public class RadioGroup:GroupBox
    {
        System.Collections.Generic.List<RadioButton> list
             = new System.Collections.Generic.List<RadioButton>();
        public RadioButton[] RadioButtons
        {
            get { return list.ToArray(); }
        }

        protected override void OnControlAdded(ControlEventArgs e)
        {
            if (e.Control is RadioButton)
                list.Add(e.Control as RadioButton);
            base.OnControlAdded(e);
        }
        protected override void OnControlRemoved(ControlEventArgs e)
        {
            if (e.Control is RadioButton)
                list.Remove(e.Control as RadioButton);
            base.OnControlRemoved(e);
        }

        public EventHandler SelectedIndexChanged;
        public int SelectedIndex
        {
            get
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].Checked) return i;
                }
                return -1;
            }
            set
            {
                if (value != SelectedIndex)
                {
                    if (value == -1)
                    {
                        list[SelectedIndex].Checked = false;

                    }
                    else
                        list[value].Checked = true;

                    if (SelectedIndexChanged != null)
                        SelectedIndexChanged(this, EventArgs.Empty);
                }
            }
        }

    }
. . .

PS, this example uses a generic list. In other words vs2005. To use in earlier versions you can use an Arraylist, although some casting will then be involved as well

posted on Wednesday, November 23, 2005 4:48 AM