早上想用ID标识来取得控件,怎么都找不到,原来不是直接在页面上,而是在web内容窗体里,继承自一个母版页,然后在debug中用快速监视寻找控件,找得焦头烂额还是没找到。最后写了一个方法,一劳永逸地解决了这个问题:
public static Control getControl(ControlCollection collection, ref Control control, String id)
{
if (collection.Count > 0)
{
for (int i = 0; i < collection.Count; i++)
{
control = collection[i];
if (control.ID != null)
{
if (id.Equals(control.ID.Trim()))
{
break;
}
}
if (control.HasControls())
{
ControlCollection collection0 = control.Controls;
control = getControl(collection0, ref control, id);
if (control != null && control.ID != null)
{
if (id.Equals(control.ID.Trim()))
{
break;
}
}
}
}
}
return control;
}
这样使用:
Control control = null;
control = getControl(Page.Controls, ref control, "ContentPlaceHolder1");
TextBox tbdate1 = (TextBox)control.FindControl("txtDate“);