问题描述
我以前用这个代码在另一个程序,但现在我无法理解为什么它不会运行我的第二个行之后的代码。
I've used this code before in another program, but now I'm having trouble understanding why it won't run the code after my second line.
foreach (Control c in Controls)
if (c.GetType() == typeof(TextBox)) //doesn't run any further
{
if ((string)c.Tag == "Filled")
{
...
}
...
}
我是不是错过了一些轻微的小细节或别的东西不正确。任何想法
I'm either missing some minor little detail or something else is incorrect. Any ideas?
编辑:?我的文本框是一个面板中
my textboxes are inside a panel.
推荐答案
当你调用 Control.Controls
,它只会在最外层返回控制。它不会递归下降到持有其他控件的容器控件。
When you call Control.Controls
, it will only return the controls at the outermost level. It won't recursively descend into any container controls that hold other controls.
如果你的控件是在另一个容器中,您将需要使用容器的> .Controls属性。
If your controls are in another container, you will need to use that container's .Controls
property instead.
另外,您可以通过编写一个方法来递归返回所有从父控件和它的所有儿童概括它,像这样:
Alternatively you can generalize it by writing a method to recursively return all the controls from the parent and all it's children, like so:
public IEnumerable<Control> AllControls(Control container)
{
foreach (Control control in container.Controls)
{
yield return control;
foreach (var innerControl in AllControls(control))
yield return innerControl;
}
}
您可以再使用,与其Control.Controls作为如下:
You can then use that instead of Control.Controls as follows:
private void test() // Assuming this is a member of a Form other class derived from Control
{
var textboxesWithFilledTag =
AllControls(this).OfType<TextBox>()
.Where(tb => (string) tb.Tag == "Filled");
foreach (var textbox in textboxesWithFilledTag)
Debug.WriteLine(textbox.Text);
}
随着评论说,我假设测试()
方法是表单中的一员,或从Control派生的类。如果不是,你将不得不父控件传递给它:
As the comment says, I'm assuming that the test()
method is a member of your Form or another class derived from Control. If it isn't, you will have to pass the parent control to it:
private void test(Control container)
{
var textboxesWithFilledTag =
AllControls(container).OfType<TextBox>()
.Where(tb => (string) tb.Tag == "Filled");
foreach (var textbox in textboxesWithFilledTag)
Debug.WriteLine(textbox.Text);
}
下面的方法具有相同的结果上面的人,以供参考(和更可读恕我直言):
The following method has identical results to the one above, for reference (and is more readable IMHO):
private void test(Control container)
{
foreach (var textbox in AllControls(container).OfType<TextBox>())
if ((string)textbox.Tag == "Filled")
Debug.WriteLine(textbox.Text);
}
有关你的代码,你的按一下按钮处理程序可能是这个样子:
For your code, your button click handler might look something like this:
void button1_Click(object sender, EventArgs e)
{
foreach (var c in AllControls(this).OfType<TextBox>())
{
if ((string) c.Tag == "Filled")
{
// Here is where you put your code to do something with Textbox 'c'
}
}
}
请注意,您还需要在 AllControls()
方法,当然。
Note that you also need the AllControls()
method, of course.
这篇关于通过文本框是不返回控制foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!