這裏是a good article on it,但下面是一個修改版本,由給定的屬性收集控制
public List<Control> ListControlCollections(Page page, string propertyName)
{
List<Control> controlList = new List<Control>();
AddControls(page.Form.Controls, controlList, propertyName);
return controlList;
}
private void AddControls(ControlCollection controlCollection, List<Control> controlList, string propertyName)
{
foreach (Control c in controlCollection) {
PropertyInfo propertyToFind = c.GetType().GetProperty(propertyName);
if (propertyToFind != null) {
controlList.Add(c);
}
if (c.HasControls()) {
AddControls(c.Controls, controlList, propertyName);
}
}
}
要使用它:
List<Control> controlList = ListControlCollections("Text");
for (i=0; i < controlList.length; i++)
{
if (controlList[i].Text == string.empty)
{
// Do your logic here
}
else
{
// Do your logic here
}
}
嘗試使用「驗證」控件(客戶端和服務器端)或JavaScript(jQuery)來驗證用戶輸入。 – adatapost
你沒有顯示任何實際的消息框是你嗎?這會在部署時造成各種問題。 –
相關:http://stackoverflow.com/questions/4955769/better-way-to-find-control-in-asp-net – jrummell