Reputation: 133
I'm trying to create some sort of forum and want to add a new div (with some text in it) every time I click the button. (this will change later on when I get everything from a database) So the idea is; click the button, div appears, click the button again, another div appears, right underneath the last one, repeating infinitely. I got as far as creating 1 div, but it won't make any more. Here's my code:
protected void Button1_Click(object sender, EventArgs e)
{
i += 1;
top += 60;
try
{
Panel div = new Panel();
div.ID = "panel" + i;
div.CssClass = "postdiv";
div.Style["position"] = "absolute";
div.Style["top"] = top.ToString();
form1.Controls.Add(div);
}
catch (Exception er)
{
Console.Write(er);
}
}
I think my problem lies with the div.Style["top"] = top.ToString(); but I'm not sure. Anyone know a solution?
Upvotes: 1
Views: 2179
Reputation: 14614
The problem is the i
and top
values will always be 0 every time you click the button, so you need to use ViewState or HiddenFields in order to keep the values between postbacks.
You'll also need to recreate the dynamically created divs in Page_Load every time a postback occurs.
Here's what I would've done using ViewState:
private int Counter
{
get
{
if (ViewState["Counter"] == null)
{
return 0;
}
else
{
return (int)ViewState["Counter"];
}
}
set
{
ViewState["Counter"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
if (this.Counter > 0)
{
for (int i = 0; i < this.Counter; i++)
{
Panel div = new Panel();
div.ID = string.Format("panel{0}", i + 1);
div.CssClass = "postdiv";
div.Style["position"] = "absolute";
div.Style["top"] = string.Format("{0}px", (60 * (i + 1)));
form1.Controls.Add(div);
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
this.Counter += 1;
try
{
Panel div = new Panel();
div.ID = string.Format("panel{0}", this.Counter);
div.CssClass = "postdiv";
div.Style["position"] = "absolute";
div.Style["top"] = string.Format("{0}px", (60 * this.Counter));
form1.Controls.Add(div);
}
catch (Exception er)
{
Console.Write(er);
}
}
Upvotes: 2
Reputation: 699
You need to take into account that each time your browser makes a round-trip to the server (be it the first or subsequent times - postbacks) the object model for the page needs to be recreated from scratch.
None of the variables, controls or objects you create in your code behind will survive a postback.
For that reason, you need to add the controls EACH TIME that the code behind is executed. That's why you need an approach as @ekad has provided. Your control generation routine needs to be inside a loop.
Upvotes: 1
Reputation: 659
Please add "px" when you assign top style:
div.Style["top"] = top.ToString() + "px";
Upvotes: 2