我开始.net并开始我将动态创建多个文本框。
我写了这个:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Page sans titre</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="OnclickButton" />
</div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
</form>
</body>
</html>
和这个
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void OnclickButton(object sender, EventArgs ea)
{
Random random = new Random();
int randomNumber = random.Next(0, 100);
Button btnSomeButton = sender as Button;
btnSomeButton.Text = "I was clicked!" + randomNumber;
TextBox txt = new TextBox();
txt.ID = "txt_" + randomNumber;
form1.Controls.Add(txt);
}
}
}
我不明白为什么当我在Button1上单击2次时,只出现1个文本框。
为什么会这样? 做我想要的好方法是什么? 提前谢谢你
答案 0 :(得分:4)
答案 1 :(得分:2)
Web状态较少。换句话说,服务器不知道有多少控件是动态添加的,除非您存储信息以便在回发后保留。
因此,您希望将数据保存到 ViewState(或SessionState) ,然后使用相同的ID重新加载 < / strong>在帖子后面。
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="Button1_Click"/>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
private List<int> ControlIds
{
get { return (List<int>) ViewState["ControlIds"] ?? new List<int>(); }
set { ViewState["ControlIds"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// Reload the controls on post back
var ids = ControlIds;
foreach (var id in ids)
{
var txt = new TextBox {ID = "txt_" + id};
form1.Controls.Add(txt);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
var random = new Random();
int randomNumber = random.Next(0, 100);
var ids = ControlIds;
if (ids.Contains(randomNumber))
{
// Randam number already exists.
// We cannot add controls with same ID.
return;
}
ids.Add(randomNumber);
ControlIds = ids;
var btnSomeButton = sender as Button;
btnSomeButton.Text = "I was clicked!" + randomNumber;
var txt = new TextBox
{
ID = "txt_" + randomNumber,
Text = randomNumber.ToString() // Just for testing
};
form1.Controls.Add(txt);
}