Reputation: 363
I begin .net and to start I will create dynamically multiple textbox.
I have write this :
<%@ 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>
and this
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);
}
}
}
I don't understand why when I click 2 time on Button1 only 1 Text Box appears.
Why this behavior? What is the good way to do what I want? thank you in advance
Upvotes: 1
Views: 1969
Reputation: 62301
Web is state less. In other words, server doesn't know how many controls are added dynamically unless you store information to persist on post back.
Therefore, you want to save the data into ViewState (or SessionState), and reload them back with same ids on post back.
<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);
}
Upvotes: 2
Reputation: 29760
Everytime you click the button it does a post back. Read this on postbacks
The system can only handle one postback at any one time. it needs to wait for the the postback to return before it can process another action.
Also read about the Page lifecycle
Upvotes: 4