在winform组框上以编程方式加载多个单选按钮

时间:2015-02-22 08:55:59

标签: c# winforms

我有一个字符串列表,我想将所有项目加载到单选按钮。用户只能从单选按钮中选择1项,然后单击继续。

代码:

            List<Control> radioButtons = new List<Control>();
            var cacheNames = GetCacheNames();
            //Lets load cache names to cachesRadioButtonsPanel
            foreach (var cacheName in cacheNames)
            {
                RadioButton radiobutton = new RadioButton();
                radiobutton.Name = cacheName;
                radiobutton.Text = cacheName;
                radioButtons.Add(radiobutton);
            }

            foreach (var singleControl in radioButtons)
            {
                cachesRadioButtonsGroupBox.Controls.Add(singleControl);
            }  

结果只有第一项可见。怎么会 ?

  • 解决方案:

            var cacheNames = GetCacheNames();
            //Lets load cache names to cachesRadioButtonsPanel
            int i=20; //pixel location
            foreach (var cacheName in cacheNames)
            {
                RadioButton radiobutton = new RadioButton();
                radiobutton.Name = cacheName;
                radiobutton.Text = cacheName;
                radiobutton.Location = new Point(10, i);
                cachesRadioButtonsGroupBox.Controls.Add(radiobutton);
                i += 20;
            }
            cachesRadioButtonsGroupBox.Height = i + 10;
    

1 个答案:

答案 0 :(得分:2)

他们都在同一个地方。您需要设置Location属性,以便将它们放在表单上的不同位置。

        List<Control> radioButtons = new List<Control>();
        var cacheNames = GetCacheNames();
        var location = new Point(0,0);
        //Lets load cache names to cachesRadioButtonsPanel
        foreach (var cacheName in cacheNames)
        {
            RadioButton radiobutton = new RadioButton();
            radiobutton.Name = cacheName;
            radiobutton.Text = cacheName;
            radiobutton.Location = location;
            radioButtons.Add(radiobutton);

            location.Y = location.Y + radiobutton.Height;
        }

        foreach (var singleControl in radioButtons)
        {
            cachesRadioButtonsGroupBox.Controls.Add(singleControl);
        }