0

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

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

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

但是,我现在需要在 FormView 控件中使用第 3 方子控件(此处为http://www.freetextbox.com的 FreeTextBox)。我将 FreeTextBox 控件称为 myFTB,并且使用了与上述类似的语句:

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

但是,这会返回 null,因此我可以为此检索属性值。

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

TIA

4

2 回答 2

0

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

尝试使用以下方法:

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;
}
于 2011-10-19T16:12:06.183 回答
0

您可以这样做以在表单视图中查找控件....

注意:下面的代码查找表单视图控件内的所有文本框

 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);
            }
        }
  }

我希望它会帮助你..

于 2011-10-19T20:24:18.300 回答