簡體   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