1.新建web項目,添加兩個Button控件,結果如圖。
2.Button按鈕控件點擊事件代碼如下
protectedvoid Button1_Click(object sender, EventArgs e) { TextBox t = newTextBox(); t.ID = "test"; t.Text = "測試框"; t.Attributes.Add("runat","server"); form1.Controls.Add(t); Response.Write(((TextBox)form1.FindControl("test")).Text); } protectedvoid Button2_Click(object sender, EventArgs e) { Response.Write(((TextBox)form1.FindControl("test")).Text); }
點擊Button1控件:
可以看到動態生成的文本框的值成功獲取到。
但是點擊Button2會出現如下結果:
原因是因為動態生成的文本框其實是HTML控件,所以獲取文本框的值 控時,要注意獲取的方法,不同時間獲取的方法不同.(頁面一加載完時的值 和 控件的原有值改變時 兩種情況)
3.代碼修改成如下即可獲取動態生成的文本框的值。
結果:
參考:https://blog.csdn.net/zheng558888/article/details/15816057