检查多个面板中的控件 [英] Checking Controls in multiple panels
问题描述
我有一个带有多个面板的程序,其中的文本框将共享一个值.例如街道地址.我编写了一种通过共享 TextChanged
事件来更新这些值的方法,但是该事件不会在面板中搜索控件,它只会影响 TextBox
主窗体窗口.
I have a programs with multiple panels with textboxes that will share a value. for example a street address. I have coded a way for these values to be updated by sharing a TextChanged
event, however the event does not search the panels for the controls, it will only affect a TextBox
in the main form window.
代码.
private void matchtextbox(object sender, EventArgs e)
{
TextBox objTextBox = (TextBox)sender;
string textchange = objTextBox.Text;
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
if (((TextBox)x).Name.Contains("textBoxAddress"))
{
((TextBox)x).Text = textchange;
}
}
}
}
所以说panel1
包含textBoxAddress1
,panel
包含textBoxAddress2
,两者都带有这个TextChanged代码>事件.他们在打字时不会相互更新.但是,如果它们在
panel
之外,它们就会这样做.
So say panel1
contains textBoxAddress1
, panel
contains textBoxAddress2
, both with this TextChanged
event. they do not update each other when typing. However if they are outside the panel
they do.
最终代码是基于下面一个可爱的社区成员的决议.
Final Code which is the resolution based on a lovely community member below.
private void Recursive(Control.ControlCollection ctrls)
{
foreach (var item in ctrls)
{
if (item is Panel)
{
Recursive(((Panel)item).Controls);
}
else if (item is TextBox)
{
if (((TextBox)item).Name.Contains("txtSAI"))
{
((TextBox)item).Text = textchange;
}
}
}
}
private void matchtextbox(object sender, EventArgs e)
{
TextBox objTextBox = (TextBox)sender;
textchange = objTextBox.Text;
Recursive(Controls);
}
string textchange;
推荐答案
你需要一个递归 用于此目的的方法:
You need a recursive method for this purpose:
private void Recursive(IEnumerable ctrls)
{
foreach (var item in ctrls)
{
if (item is Panel)
{
Recursive(((Panel)item).Controls);
}
else if(item is TextBox)
{
if (((TextBox)item).Name.Contains("textBoxAddress"))
{
((TextBox)item).Text = textchange;
}
}
}
}
然后这样称呼它:
private void matchtextbox(object sender, EventArgs e)
{
Recursive(Controls);
}
这篇关于检查多个面板中的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!