如何通过名称从 textBox 中获取值?
How to get value from textBox by its name?
我正在尝试使用 Control class 按名称从 textBox 获取值?
有我的代码:
Control ctl = FindControl(this, "B1");
if (ctl is TextBox)
listBox1.Items.Add(((TextBox)ctl).Text);
//"B1" - 这是文本框名称
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;
}
问题是编译器没有进入函数。
可能是什么问题?
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 控件。
尝试改用控件实例的 ID 属性。如果我们谈论的是 System.Web.UI 命名空间,我不确定名称 属性 是否可用于控件 class。
对于 WinForms,您只需执行以下操作:
Control ctl = this.Controls.Find("B1", true).FirstOrDefault();
if (ctl != null)
{
// use "ctl" directly:
listBox1.Items.Add(ctl.Text);
// or if you need it as a TextBox, then cast first:
if (ctl is TextBox)
{
TextBox tb = (TextBox)ctl;
// ... do something with "tb" ...
listBox1.Items.Add(tb.Text);
}
}
您不需要自己的递归搜索功能...
我正在尝试使用 Control class 按名称从 textBox 获取值? 有我的代码:
Control ctl = FindControl(this, "B1");
if (ctl is TextBox)
listBox1.Items.Add(((TextBox)ctl).Text);
//"B1" - 这是文本框名称
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;
}
问题是编译器没有进入函数。 可能是什么问题?
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 控件。
尝试改用控件实例的 ID 属性。如果我们谈论的是 System.Web.UI 命名空间,我不确定名称 属性 是否可用于控件 class。
对于 WinForms,您只需执行以下操作:
Control ctl = this.Controls.Find("B1", true).FirstOrDefault();
if (ctl != null)
{
// use "ctl" directly:
listBox1.Items.Add(ctl.Text);
// or if you need it as a TextBox, then cast first:
if (ctl is TextBox)
{
TextBox tb = (TextBox)ctl;
// ... do something with "tb" ...
listBox1.Items.Add(tb.Text);
}
}
您不需要自己的递归搜索功能...