查找文本框控件
问题描述:
在我的应用程序中,我有50个文本框,我想查找所有使用该代码的文本框控件,并且我想在执行特定验证后在文本框中执行颜色更改。我该如何实现这个目标?我用下面的代码,但它不正常工作查找文本框控件
foreach (Control cntrl in Page.Controls)
{
if (cntrl is TextBox)
{
//Do the operation
}
}
<%@页面语言= “C#” 的MasterPageFile = “〜/ HomePageMaster.master” AutoEventWireup = “真” 的CodeFile = “Default.aspx.cs”继承= “默认” 名称= “示例页面” %>
答
protected void setColor(Control Ctl)
{
foreach (Control cntrl in Ctl.Controls)
{
if (cntrl.GetType().Name == "TextBox")
{
//Do Code
}
setColor(Control cntrl);
}
}
然后,您可以用的setColor(页)称之为
答
我最近开始这样做'现代'的LINQ方式。首先,你需要一个扩展的方法来抓住你感兴趣的所有类型的控件:
//Recursively get all the formControls
public static IEnumerable<Control> GetAllControls(this Control parent)
{
foreach (Control control in parent.Controls)
{
yield return control;
foreach (Control descendant in control.GetAllControls())
{
yield return descendant;
}
}
}`
然后,你可以把它在你的表单/控制:
var formCtls = this.GetAllControls().OfType<Checkbox>();
foreach(Checkbox chbx in formCtls){
//do what you gotta do ;)
}
Regards,
5arx
+0
,扩展方法必须在非静态泛型类中定义。 – Fawad 2016-01-02 13:36:48
答
这是递归的,所以它会在页面中的所有控件上运行。 请注意,如果您想让它遍历数据绑定控件中的文本框,您应该可以在OnPreRender中调用它。
protected void Page_Load(object sender, EventArgs e)
{
ColorChange(this);
}
protected static void ColorChange(Control parent)
{
foreach (Control child in parent.Controls)
{
if (child is TextBox)
(child as TextBox).ForeColor = Color.Red;
ColorChange(child);
}
}
对我来说看起来很对,因为这样做不会进行递归搜索,所以如果您的页面中有容器控件,那么将不会找到任何文本框。 “你无法正常工作”是什么意思? – Oded 2010-12-14 10:37:47
我觉得Oded是对的,你最有可能在容器控件中获得它们 – 2010-12-14 10:39:34
可以通过SO链接http://stackoverflow.com/questions/4321458/enumerate-all-controls-in-the-form/4333243# 4333243 – dhinesh 2010-12-14 10:49:00