我使用這個代碼點擊一個按鈕
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="addnewtext" runat="server" Text="Add" onclick="addnewtext_Click" width="76px" />
和aspx.cs頁面代碼時動態添加一個新的文本框添加另一個文本框。
我使用這個代碼點擊一個按鈕
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="addnewtext" runat="server" Text="Add" onclick="addnewtext_Click" width="76px" />
和aspx.cs頁面代碼時動態添加一個新的文本框添加另一個文本框。
原因: 當你再次點擊按鈕比它做回發到服務器端,並去除了以前添加的動態文本框
解決方案: 要重新添加它,你需要做這樣的
TextBox tb;
static int i = 0;
protected void addnewtext_Click(object sender, EventArgs e)
{
i++;
for(j=0;j<=i;j++)
{
tb = new TextBox();
tb.ID = j.ToString();
PlaceHolder1.Controls.Add(tb);
}
}
這意味着您需要再次創建添加的文本框......因爲您正在動態添加控件到頁面......
文章這樣可以幫助你:Retaining State for Dynamically Created Controls in ASP.NET applications
讓我們從一個列表視圖
<asp:ListView ID="lvDynamicTextboxes" runat="server"
ItemPlaceholderID="itemPlaceholder"> <LayoutTemplate> <table> <asp:PlaceHolder ID="itemPlaceholder"
runat="server"></asp:PlaceHolder> </table> </LayoutTemplate> <ItemTemplate> <tr> <asp:TextBox ID="txtText" runat="server"> </asp:TextBox> </tr> </ItemTemplate>
</asp:ListView>
<asp:Button ID="btnAddTextBox" runat="server"
Text="Add" onclick="btnAddTextBox_Click" />
一些守則
private void BindListView()
{
//get the current textbox count int count = 1;
if (ViewState["textboxCount"] != null)
count = (int)ViewState["textboxCount"];
//create an enumerable range based on the current count IEnumerable<int> enumerable = Enumerable.Range(1, count);
//bind the listview this.lvDynamicTextboxes.DataSource = enumerable;
this.lvDynamicTextboxes.DataBind();
}
private void IncrementTextboxCount()
{
int count = 1;
if (ViewState["textboxCount"] != null)
count = (int)ViewState["textboxCount"];
count++;
ViewState["textboxCount"] = count;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.BindListView();
}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
this.IncrementTextboxCount();
this.BindListView();
}
現在去要提取值從這些新增的文本框:
private IList<string> GetValues()
{
List<string> values = new List<string>();
TextBox txt = null;
foreach (ListViewItem item in this.lvDynamicTextboxes.Items)
{
if (item is ListViewDataItem)
{
txt = (TextBox)item.FindControl("txtText");
values.Add(txt.Text);
}
}
return values;
}
現在打開另一個選項卡中的同一頁面,並嘗試點擊兩個... – CyberDude
@CyberDude - 我離開了OP的,但你可以檢查這個更多的細節:http://www.codeproject.com/Articles/3684/Retaining-State-for-Dynamically-Created-Controls-i –
不,這不是另一個問題,它是您答案中的根本問題。您似乎對靜態變量的瞭解與他在回發和查看狀態中所做的一樣。造成另一個更大問題的解決方案不是解決方案。 – CyberDude