繁体   English   中英

ASP.Net在FormView控件中访问子控件

[英]ASP.Net Accessing child controls in a FormView control

我正在使用带有EditItemTemplate的FormView控件(myFormView),该控件包含许多子控件。 当我使用标准ASP.Net DropDownList控件(myDropList)时,可以使用下面的行获取对myDropList的引用:

((DropDownList)myFormView.FindControl("myDropList"))

我可以完全访问myDropList的属性并获取当前选择的值。 这很棒。

但是,我现在需要在FormView控件中使用第3方子控​​件(在此处可以找到FreeTextBox, 网址http://www.freetextbox.com )。 我已经将FreeTextBox控件称为myFTB,并且使用的是上面类似的语句:

((FreeTextBox)myFormView.FindControl("myFTB"))

但是,此方法返回null,因此可以检索此属性值。

有谁知道为什么它返回null? 还有其他方法可以检索对控件的引用吗?

TIA

您将需要使用递归在控件层次结构中找到控件。

尝试使用以下方法:

FreeTextBox textBox = (FreeTextBox)FindControl(myFormView, "myFTB");

...

private Control FindControl(Control parent, string id)
{
    foreach (Control child in parent.Controls)
    {
        string childId = string.Empty;
        if (child.ID != null)
        {
            childId = child.ID;
        }

        if (childId.ToLower() == id.ToLower())
        {
            return child;
        }
        else
        {
            if (child.HasControls())
            {
                Control response = FindControl(child, id);
                if (response != null)
                    return response;
            }
        }
    }

    return null;
}

您可以像这样在窗体视图中查找控件。

注意:以下代码在窗体视图控件中找到所有文本框

 protected void FormView1_DataBound(object sender, EventArgs e)
 {
        if (FormView1.CurrentMode == FormViewMode.Edit)
        {
            FindAllTextBoxes(FormView1);
        }
 }

 private void FindAllTextBoxes(Control parent)
 {
        foreach (Control c in parent.Controls)
        {
            if (c.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
            {
                TextBox tbox = c as TextBox;
                if (tbox != null)
                {
                    // textbox found ....you could send this textbox, by reference to another procedure that assigns the values comparing
                    //it by tbox.ID
                }
            }
            if (c.Controls.Count > 0)
            {
                FindAllTextBoxes(c);
            }
        }
  }

希望对您有帮助。

暂无
暂无

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

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