使数组包含窗体上的所有控件 [英] make a array contains all the controls on the form

查看:87
本文介绍了使数组包含窗体上的所有控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我对C#有问题.例如,我的项目有一个包含一个按钮和一个文本框的表单.我可以制作一个包含按钮和文本框的数组(示例名为"arr").当我使用按钮时或文本框,我使用arr [0]或arr [1].
谢谢!

hi everybody,i have some problem with C#.Example,my project have a form which contains one button and one textbox.Can i make a array(example named "arr") contains the button and textbox.When i use button or textbox,i use arr[0] or arr[1].
Thanks!

推荐答案

.Net中的控制数组是您真正不需要的.
但是,在Visual Basic .NET和Visual C#.NET中创建控件数组 [ ^ ]应该可以帮助您,以防万一.
Control Arrays in .Net is something that you should not really require.
However, Creating Control Arrays in Visual Basic .NET and Visual C# .NET[^] should help you out in case if you do want to do this.


是的,您可以使用现在已经过时且非常有限的类型,键入``Array to hold Controls
Yes, you can use that now rather outdated, and very limited, type ''Array to hold Controls
Control[] BunchAControls = new Control[];
//
BunchAControls[0] = textBox1;
BunchAControls[1] = button1;

或者,您可以使用至少支持''AddRange:

Or, you could use the ControlCollection object which at least supports ''AddRange:

// at your application top-level''s Form scope
ControlCollection cCollection;
//
// you have to initialize a ControlCollection inside a Form instance because a Form instance reference must be supplied as a parameter to the ControlCollection constructor.
//
// example: in a Form Load event:
cCOllection = new ControlCollection(this);
//
cCollection.Add(textBox1);
cCollection.Add(button1);

的ControlCollection对象,或者您可以使用现代的并使用通用的List< Control>:

Or you could get modern and use a generic List<Control>:

List<control> lControls = new List<Control>();
lControls.AddRange { textBox1, button1 };</control>

,但是,这里要问的主要问题是为什么您想要这样的控件集合:

1.由于该集合仅包含所有控件共享的通用"属性和方法:如果要访问唯一的属性或方法,例如对于TextBox,则与Button相比:您必须转换控件返回其最终"类型以暴露那些属性,方法等.这意味着强制转换,通常应避免这种情况.

现在,您可能有很好的战略原因来制作数组,集合或通用控件列表.如果您分享自己的目标,请在这里.希望我们能提出一些有创意的建议.

Bill,祝你好运

But, the big question to ask here is why you want such a collection of Controls:

1. since the collection contains only those "common" properites and methods shared by all Controls: if you want to access properties or methods unique, say, for a TextBox ... compared to Button: you''ll have to convert the Control back to its "finalized" Type to expose those properties, methods, etc. Which means casting, which is usually something to be avoided.

Now, you may have a very good strategic reason to make an Array, Collection, or generic List of Controls. If you share what your goal is, here. Hopefully we can make some creative suggestions.

good luck, Bill


这篇关于使数组包含窗体上的所有控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆