[英]How will I get a dynamic control in an aspx page?
我正在為我的公司工作。 在那里我遇到了一個問題。 因此,我展示了一個我打算做的事和我不能做的事的例子。
在我的aspx頁面中,有按鈕和占位符。 例如
<asp:Button ID = "brnClickme" runat = "server" Text = "Click Me"onclick="brnClickme_Click" />
<asp:PlaceHolder ID = "PH" runat = "server"></asp:PlaceHolder>
在我的aspc.cs文件中,我有一個動態控件,比如說一個Label,它將在單擊Button后更改其值。
所以我寫了這樣的代碼
protected void Page_Init(object sender, EventArgs e)
{
Label label = new Label();
label.Text = "I am in the Place holder";
PH.Controls.Add(label);
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void brnClickme_Click(object sender, EventArgs e)
{
Label label = (Label)FindControl("label");
label.Text = "After Click I am changed!";
}
但是在“按鈕單擊”事件中,找不到標簽,因此無法通過單擊更改此動態創建的標簽的文本。 我知道我犯了一個錯誤,所以請告訴我我犯了什么錯誤以及我打算做什么。
提前致謝
嘗試在占位符中找到控件
PH.FindControl("label");
您可能希望為標簽指定一個ID,以便在創建標簽時更容易找到它。
label.ID = "findme";
然后
PH.FindControl("findme");
創建控件時,您沒有給它一個ID
- FindContorl
使用該ID
來查找該控件。
正如podiluska 回答的那樣,您還應該在添加到容器的容器上調用FindControl
(在您的情況下為PH
)。
protected void Page_Init(object sender, EventArgs e)
{
Label label = new Label();
label.ID = "myLabel";
label.Text = "I am in the Place holder";
PH.Controls.Add(label);
}
protected void brnClickme_Click(object sender, EventArgs e)
{
Label label = (Label)PH.FindControl("myLabel");
label.Text = "After Click I am changed!";
}
您必須已經在INIT中重新創建動態控件。 當您在Button中搜索LABEL時,請嘗試嘗試調用templateFormPlaceholder.FindControl
。
讀這個。 它可能有助於從asp.net中動態創建的文本框中獲取文本
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.