如何从textBox的名称中获取价值? [英] How to get value from textBox by its name?
问题描述
我想使用Control类通过textBox的名称获取值吗?有我的代码:
I am trying to get value from textBox by its name using Control class? There is my code:
Control ctl = FindControl(this,"B1");如果(ctl是TextBox)listBox1.Items.Add((((TextBox)ctl).Text);
//"B1"-它是文本框名称
Control ctl = FindControl(this, "B1");
if (ctl is TextBox)
listBox1.Items.Add(((TextBox)ctl).Text);
//"B1" - it's textBox name
public static Control FindControl(Control parent, string ctlName)
{
foreach (Control ctl in parent.Controls)
{
if (ctl.Name.Equals(ctlName))
{
return ctl;
}
FindControl(ctl, ctlName);
}
return null;
}
问题在于编译器没有进入该函数.可能是什么问题?
The problem is that the compiler does not go into the function. What could be the problem?
推荐答案
public Form1()
{
InitializeComponent();
B1.Text = "LOL";
Control ctl = FindControl(this, "B1");
if (ctl is TextBox)
listBox1.Items.Add(((TextBox)ctl).Text);
}
public static Control FindControl(Control parent, string ctlName)
{
foreach (Control ctl in parent.Controls)
{
if (ctl.Name.Equals(ctlName))
{
return ctl;
}
FindControl(ctl, ctlName);
}
return null;
}
如果您像上面的示例中那样操作,那么一切都很好.
我想您使用Windows Froms.
P.S.我没有50的声誉,因此无法发表评论.
正确答案
如果TextBoxes位于FlowLayout上,则父级为FlowLayout,并且您需要在Control ctl = FindControl(this,"B1");行中使用FlowLayout名称而不是"this".因为"this"是MainWindow控件.
If you did it like in sample above then all be right.
I suppose you use Windows Froms.
P.S. I can't write a commentary because I haven't 50 reputation.
Correct Answer
If TextBoxes are on the FlowLayout then the parent is FlowLayout and you need use the FlowLayout name instead of "this" in line Control ctl = FindControl(this, "B1");. Because "this" it's the MainWindow control.
这篇关于如何从textBox的名称中获取价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!