繁体   English   中英

如何动态获取aspx页面中的所有控件(及其ID)?

[英]How to Dynamically get All controls (and it's IDs) in an aspx Page?

嗨,我需要根据将要执行的服务在页面中动态激活字段...

让我解释:

有一个页面包含所有可能的字段,还有一个列表框,其中包含所有要执行的选定服务,然后,当用户选择要执行的服务(例如,更换车牌)时,我只需要激活该字段即可服务需要...(服务和字段之间的关系存储在数据库中)。

public void CheckAll(int pService_Id, Control pPage)
{

    foreach (Control control in pPage.Controls)
    {
        busExecutaServico vExecuta = new busExecutaServico();

        if (vExecuta.EnableField(control.ID.ToString(), Convert.ToInt32(listBoxServices.SelectedValue)))
        {
            switch (control.GetType().ToString())
            {
                case "TextBox":
                    TextBox controleText = (TextBox)Page.FindControl(control.ID.ToString());
                    controleText.Enabled = true;
                    break;

请注意,busExecutaServico是包含用于检查所选项目是否与数据库中的任何字段匹配的方法(EnableField)的类。

我似乎无法使control.ID.ToString()正常工作(ID始终为NULL)

如果有人可以帮助我解决此问题,或者有另一种方法(即使它与我尝试的方法完全不同),那将是非常有帮助的。 谢谢

我喜欢使用递归函数来按类型或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;
}

您可以调整它们以首先返回控件集合,然后再处理它们。 可能更容易跟踪正在发生的事情。

我在这里学习了这种技术: http : //www.west-wind.com/Weblog/posts/5127.aspx

请注意,FindControl仅搜索当前的命名容器,因此Page.FindControl将仅查找直接添加到Page的控件。 例如,如果您的转发器控件具有要查找的控件并将其添加到Page中,则可以通过Page.FindControl找到转发器控件,但是在转发器中找不到子控件,您将拥有在页面上的所有容器控件上递归执行FindControl。

这似乎有些奇怪,但是它使您可以在同一页面上使用具有相同ID的控件。 例如,如果您有一个用户控件的实例,其中有10个带有“ MyName”的文本框,则您真的希望它们不要覆盖彼此的“ MyName”字段!

除非为每个控件指定了ID,否则您的代码的ID将为空。

还有为什么使用:-

TextBox controleText = (TextBox)Page.FindControl(control.ID.ToString());

完全代替:

TextBox controleText = (TextBox)control;

实际上,由于您只想更改Enabled属性,请考虑:

((WebControl)control).Enabled = False;

我怀疑会消除许多案件陈述。

在您的代码中,您不需要搜索任何控件-您已经在'control'变量中找到了它。 您甚至不需要将其强制转换为TextBox,仅强制转换为WebControl,只需执行以下操作:

...
if (vExecuta.EnableField(control.ID.ToString(), Convert.ToInt32(listBoxServices.SelectedValue)))
    ((WebControl)control).Enabled = true;

PS control.ID已经是字符串,因此您也应该删除所有ID.ToString()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM