2012-11-21 61 views
4

我使用这个代码点击一个按钮

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder> 
<asp:Button ID="addnewtext" runat="server" Text="Add" onclick="addnewtext_Click" width="76px" /> 

aspx.cs页面代码时动态添加一个新的文本框添加另一个文本框。

回答

6

原因: 当你再次点击按钮比它做回发到服务器端,并去除了以前添加的动态文本框

解决方案: 要重新添加它,你需要做这样的

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

+0

现在打开另一个选项卡中的同一页面,并尝试点击两个... – CyberDude

+0

@Cyber​​Dude - 我离开了OP的,但你可以检查这个更多的细节:http://www.codeproject.com/Articles/3684/Retaining-State-for-Dynamically-Created-Controls-i –

+1

不,这不是另一个问题,它是您答案中的根本问题。您似乎对静态变量的了解与他在回发和查看状态中所做的一样。造成另一个更大问题的解决方案不是解决方案。 – CyberDude

0

让我们从一个列表视图

<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; 
}