HotDog's Blog

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

This blog hosted by:
http://blogs.vbcity.com      
  Home :: Syndication  :: Login

OctNovember 2005Dec
SMTWTFS
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

Articles

Archives

Topics

CONTACT

Fun but useful linkies

General

VS 2005

Wolfenstein ET

Wednesday, November 23, 2005 #

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 @ 4:48 AM