【问题标题】:How to create hundreds of radiobuttons using For loop?如何使用 For 循环创建数百个单选按钮?
【发布时间】:2012-04-12 12:42:11
【问题描述】:

我正在尝试在窗口窗体上使用 for 循环创建许多单选按钮。我面临的问题是为每个单选按钮生成一个变量名。最初,我计划为每个单选按钮添加不同的数字,例如 0001 、 0002 。但是,我不能这样做,因为变量名不是字符串。有什么建议吗?

【问题讨论】:

  • 表单上的“数百个”控件会遇到严重的性能问题。而且您的用户会非常适合,因为该界面根本没有“可用”的东西。但这很容易做到,就像你描述的那样。你是什​​么意思“变量名不是字符串”?是的。查找单选按钮控件的Name 属性。
  • @CodyGray 我打算将这些按钮放入带有滚动条的面板中。
  • @CodyGray 我知道有这样的名称字段->radioButton1->Name = L"radioButton1"; . L"radioButton1" 是字符串,但 (this->radioButton1->Name) 中的 radioButton1 不是字符串。我应该如何处理?
  • 好吧,没关系。您可以重复使用相同的变量名称来创建循环中的所有对象。如果您需要保留通过代码单独访问它们的能力,您可以在遍历循环时将它们放入一个数组中(类似于List<RadioButton>)。 (我只是写一些示例代码并发布答案,但我告诉自己在 iPhone 上编写 cmets 更容易......如果我以后记得的话。)

标签: .net winforms c++-cli radio-button


【解决方案1】:

使用数组:

RadioButton[] rb = new RadioButton[100];
for (int i = 0; i < 100; i++)
{
    rb[i] = new RadioButton();
    rb[i].Location = new Point(0, i * 20);
    rb[i].Text = "Your text here";
    groupBox1.Controls.Add(rb[i]);
    //etc.
}

这是用 C# 编写的,因为我不懂 VC++,但也许它可以帮助你。

【讨论】:

  • 我不明白的一件事是如何在组框上添加每个单选按钮?我很困惑应该有像“this->groupBox1->Controls->Add(this->radioButton4);”这样的语句不是吗?您使用 for 循环来创建,但它们并不是真正要显示的东西。我对吗?很抱歉我对 VC++ 很陌生。
  • @Marco 我将其添加到我的答案中。并且还纠正了我没有自己创建 RadioButtons 的原始答案中的一个错误。同样,这是在 C# 中。
【解决方案2】:

试试这个:

        var rb = new List<RadioButton>();
        bool Satisfied = false; int location =0;

        while (!Satisfied)
        {
            rb.Add(new RadioButton() { Location = new Point(0, location * 20), Text = location.ToString() });
            location++;
            Satisfied = rb.Count > 100 ? true : false;
        }


        foreach ( object r in rb)
        {
            this.Controls.Add((RadioButton)r);
        }

【讨论】:

    猜你喜欢
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 2017-12-19
    • 1970-01-01
    • 2021-12-26
    • 2021-05-12
    相关资源
    最近更新 更多