C# 如何在 WinForms 中获取控件索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/375223/
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
How to get control index in WinForms?
提问by Michael Itzoe
I have a Panel with a collection of controls in it. How can I get the index of a specific control when iterating through them? I'm using foreach
to iterate, but there's no Index property. Should I use for x = 0...
and return x
when my match is made, or what?
我有一个面板,里面有一组控件。迭代它们时如何获取特定控件的索引?我正在使用foreach
迭代,但没有 Index 属性。我应该在匹配时使用for x = 0...
并返回x
,还是什么?
回答by Steven Behnke
You could use:
你可以使用:
panel.Controls.IndexOf(control);
Or you could iterate over them with a for loop instead of a foreach loop. Or you could just create an index that you increment inside of the foreach loop.
或者您可以使用 for 循环而不是 foreach 循环遍历它们。或者您可以创建一个在 foreach 循环内递增的索引。
回答by BFree
You can just use the IndexOf method. Something like panel1.Controls.IndexOf(textBox1);
您可以只使用 IndexOf 方法。类似于 panel1.Controls.IndexOf(textBox1);
回答by AlfredBr
To answer the specific question you asked, yes, I'd use
要回答您提出的具体问题,是的,我会使用
for(x = 0; x < panel.Controls.Count; i++)
for(x = 0; x < panel.Controls.Count; i++)
However, if you are dynamically ading controls to the panel, you might consider giving them unique names or other identifing attributes via the .Name or .Tag properties.
但是,如果您正在向面板动态添加控件,您可能会考虑通过 .Name 或 .Tag 属性为它们提供唯一的名称或其他标识属性。
Then you can discriminate among your child controls with more precision.
然后,您可以更精确地区分子控件。
Hope this helps...
希望这可以帮助...