C# 如何在aspx页面中动态获取所有控件(及其ID)?
您好,我需要根据要执行的服务动态激活页面中的字段 让我解释一下: 有一个包含所有可能字段的页面和一个包含所有要执行的选定服务的列表框,然后当用户选择要执行的服务(例如更改车牌)时,我只需要激活该服务所需的字段。。。(服务和字段之间的关系存储在数据库中) 请注意,busExecutaServico是一个类,它包含用于检查所选项是否与数据库中的任何字段匹配的方法(EnableField) 我似乎无法使控件.ID.ToString()正常工作(ID始终为NULL)C# 如何在aspx页面中动态获取所有控件(及其ID)?,c#,asp.net,visual-studio-2008,C#,Asp.net,Visual Studio 2008,您好,我需要根据要执行的服务动态激活页面中的字段 让我解释一下: 有一个包含所有可能字段的页面和一个包含所有要执行的选定服务的列表框,然后当用户选择要执行的服务(例如更改车牌)时,我只需要激活该服务所需的字段。。。(服务和字段之间的关系存储在数据库中) 请注意,busExecutaServico是一个类,它包含用于检查所选项是否与数据库中的任何字段匹配的方法(EnableField) 我似乎无法使控件.ID.ToString()正常工作(ID始终为NULL) 如果有人能帮我解决这个问题,或者有另
如果有人能帮我解决这个问题,或者有另一种方法(即使它与我正在尝试的完全不同),那将是非常有帮助的。感谢请注意,FindControl仅搜索当前命名容器,因此Page.FindControl将仅查找直接添加到Page的控件。例如,如果您有一个中继器控件,该控件包含您要查找的控件,并已添加到页面中,则可以通过Page.FindControl找到中继器控件,但在中继器中找不到子控件,则必须递归地对页面中的所有容器控件执行FindControl
这可能看起来有点奇怪,但它允许在同一页上存在具有相同ID的控件。例如,如果您有10个用户控件实例,其中包含名为“MyName”的文本框,那么您真的希望它们不会过度写入彼此的“MyName”字段 在您的代码中,您不需要搜索任何控件-您已经在“control”变量中找到了它。您甚至不需要将其强制转换为文本框,只需将其转换为网络控件,只需执行以下操作:
...
if (vExecuta.EnableField(control.ID.ToString(), Convert.ToInt32(listBoxServices.SelectedValue)))
((WebControl)control).Enabled = true;
p.S.control.ID已经是字符串,因此您也应该删除任何ID.ToString()。除非每个控件都有一个ID,否则代码中的ID将为null 为什么要使用:-
TextBox controleText = (TextBox)Page.FindControl(control.ID.ToString());
而不是:-
TextBox controleText = (TextBox)control;
事实上,由于您只想更改Enabled属性,请考虑:-
((WebControl)control).Enabled = False;
我怀疑这将消除许多case语句。我喜欢使用递归函数按类型或ID定位控件
public Control FindControlRecursive(Control rootControl, string controlId)
{
if (rootControl.ID == controlId)
return rootControl;
foreach (Control control in rootControl.Controls)
{
Control foundControl = FindControlRecursive(control, controlId);
if (foundControl != null)
{
return foundControl;
}
}
return null;
}
public Control FindControlRecursive(Control rootControl, Type type)
{
if (rootControl.GetType().Equals(type))
return rootControl;
foreach (Control control in rootControl.Controls)
{
Control foundControl = FindControlRecursive(control, type);
if (foundControl != null)
{
return foundControl;
}
}
return null;
}
您可以对其进行调整,以首先返回控件集合,然后再对其进行处理。可能更容易跟踪正在发生的事情
我在这里学到了这项技术:嗯,控件已经在页面中了。。。我只在数据库中存储了它的名称。。因此,我可以检查control.ID是否与数据库中存储的ID匹配
public Control FindControlRecursive(Control rootControl, string controlId)
{
if (rootControl.ID == controlId)
return rootControl;
foreach (Control control in rootControl.Controls)
{
Control foundControl = FindControlRecursive(control, controlId);
if (foundControl != null)
{
return foundControl;
}
}
return null;
}
public Control FindControlRecursive(Control rootControl, Type type)
{
if (rootControl.GetType().Equals(type))
return rootControl;
foreach (Control control in rootControl.Controls)
{
Control foundControl = FindControlRecursive(control, type);
if (foundControl != null)
{
return foundControl;
}
}
return null;
}