[英]ASP.NET dynamically created textbox doesn't change value
我有以下問題:我在網頁中動態創建一個TextBox,其開頭的值為“ initialVal”。 現在,我需要對服務器進行回發(而不是回調),並且在此操作期間,我需要將文本框的值計算/更改為其他值。
這是一個例子:
protected void Page_Load(object sender, EventArgs e)
{
TextBox txtBox = new TextBox();
txtBox.ID = "newButton";
form1.Controls.Add(txtBox);
txtBox.Text = "initialVal";
if (IsPostBack && Session["change"] == null)
{
txtBox.Text = "change";
Session["change"] = true;
}
}
問題:即使我通過代碼更改了值,文本框也會保留文本“ initialVal”。 我覺得這與視圖狀態有關,但我不明白。 庫德爾有人請在這里幫助我嗎?
謝謝。
在!IsPostBack中創建動態文本框
protected void Page_Load(object sender, EventArgs e)
{
if(!isPostBack){
TextBox txtBox = new TextBox();
txtBox.ID = "newButton";
form1.Controls.Add(txtBox);
txtBox.Text = "initialVal";
}
if (IsPostBack && Session["change"] == null)
{
txtBox.Text = "change";
Session["change"] = true;
}
}
謝謝,讓我知道您的問題是否仍未解決
每次加載頁面時,它都會運行以下命令:
txtBox.Text = "initialVal";
您應該將其包裝在檢查中以進行回發:
if (!Page.IsPostback)
{
txtBox.Text = "initialVal";
}
就是說, onLoad
是進行創建的錯誤事件,要使其在頁面生命周期的足夠早的時間內有效,請使用OnInit
。
請參閱MSDN上的這篇文章 。
這是@ user2890888的最終代碼:
public partial class WebForm1 : System.Web.UI.Page
{
TextBox txtBox = null;
protected void Page_Init(object sender, EventArgs e)
{
txtBox = new TextBox();
txtBox.ID = "newButton";
form1.Controls.Add(txtBox);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtBox.Text = "initialVal";
}
if (IsPostBack && Session["change"] == null)
{
txtBox.Text = "change";
Session["change"] = true;
}
}
}
找到TextBox
並使用它
TextBox txtBox = (TextBox)FindControl("txtBox");
txtBox.Text = "change";
即使現在您遇到了問題,您的textBox也無法獲得所需的值。 將您的TEXTBOX新值存儲在一個hiddenfield中。 我的意思是 ,
if (IsPostBack && Session["change"] == null)
{
hiddenfield1.value = "change";
}
然后在頁面腳本中,您可以將此hiddenfield1中的值重新分配給文本框。
$(document).ready(
{
$('#txtBoxID').value=$('#hiddenfield1').value;
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.