C# 动态添加复选框到 Windows 窗体只显示一个复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15005333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically Adding Checkboxes to a Windows Form Only Shows one Checkbox
提问by Chris Ruskai
I'm sorry if this seems n00bish, but I have been searching for this for a few days now. I am attempting to dynamically add checkboxes to a windows form; however, only one checkbox appears on the form. Here is my code:
如果这看起来不合适,我很抱歉,但我已经搜索了几天了。我正在尝试将复选框动态添加到 Windows 窗体中;但是,表单上只显示一个复选框。这是我的代码:
for (int i = 0; i < 10; i++)
{
box = new CheckBox();
box.Tag = i.ToString();
box.Text = "a";
box.AutoSize = true;
box.Location = new Point(10, i + 10);
Main.Controls.Add(box);
}
As you can see I am adding the checkboxes via a for loop. I have tried messing with the location and enabling autosize in case they were somehow overlapping. The result is a single checkbox with text "a".
如您所见,我正在通过 for 循环添加复选框。我曾尝试弄乱位置并启用自动调整大小,以防它们以某种方式重叠。结果是一个带有文本“a”的复选框。
采纳答案by spajce
Actually you already created a CheckBox
but within the same point.
实际上你已经创建了一个CheckBox
但在同一点内。
CheckBox box;
for (int i = 0; i < 10; i++)
{
box = new CheckBox();
box.Tag = i.ToString();
box.Text = "a";
box.AutoSize = true;
box.Location = new Point(10, i * 50); //vertical
//box.Location = new Point(i * 50, 10); //horizontal
this.Controls.Add(box);
}
回答by Sheela K R
In this case with help of dynamically assign Name property how to achive checkbox.checked property , in some other action like submit button. how can i get all check box is checked and which is created in loop?
在这种情况下,在动态分配 Name 属性的帮助下,如何在提交按钮等其他一些操作中实现 checkbox.checked 属性。我怎样才能让所有复选框都被选中并在循环中创建?
回答by Dokman
If you have an instance from every button you can make with your button or your event to make something like
如果你有每个按钮的实例,你可以用你的按钮或你的事件来制作类似的东西
CheckBox myCheckedBox = (CheckBox)sender;