protected void QueryBox1_AddEvent(Object sender, EventArgs e)
{
QueryBoxCount++;
QueryBox qb = (QueryBox)LoadControl("QueryBox.ascx");
qb.AddEvent += new EventHandler(QueryBox1_AddEvent);
this.Panel1.Controls.Add(qb);
}
This works perfectly! For some reason I thought if I created controls
anywhere other than during the load event they would be destroyed on
post back. Shows what I know huh?
Please note you could use ViewState to store the counter internally instead
of textbox (but i quess in your current solution user can enter number of
QueryBoxes to display)
I didn't know I could use ViewState - I thought my only options where a
hidden field or a session variable. If you have time could you explain
how I could use ViewState here? I'm a complete beginner at this (I've
only ran through some basic tutorials).
Thanks again!
Milosz wrote:
Hi,
You cannot move creation of the controls anywhere (i.e. prerender) because
event would not be raised, therefore you could recreate controls everytime
counter changes or just add one more to the panel:
protected void QueryBox1_AddEvent(Object sender, EventArgs e)
{
QueryBoxCount++;
QueryBox qb = (QueryBox)LoadControl("QueryBox.ascx");
qb.AddEvent += new EventHandler(QueryBox1_AddEvent);
this.Panel1.Controls.Add(qb);
}
or
protected void QueryBox1_AddEvent(Object sender, EventArgs e)
{
QueryBoxCount++;
this.Panel1.Controls.Clear();
for (Int16 i = 1; i <= QueryBoxCount; i++)
{
QueryBox qb = (QueryBox)LoadControl("QueryBox.ascx");
qb.AddEvent += new EventHandler(QueryBox1_AddEvent);
this.Panel1.Controls.Add(qb);
}
}
Please note you could use ViewState to store the counter internally instead
of textbox (but i quess in your current solution user can enter number of
QueryBoxes to display)
--
Milosz
"ju*************@yahoo.com" wrote:
This has to be simple, but I can't seem to grasp what I'm doing wrong!
I have a user control that contains a button that when clicked raises a
"AddEvent". When this fires I want the host page to add another of the
user controls to the page.
I'm tracking the number of controls to load in a textbox on the page
(wrapped in a property) and doing a for loop in the page_load. The
problem is that the addevent is processed after the load event and
therefore the number of controls is 1 behind what it should be.
Can someone please tell me what I'm doing wrong here? Or if there is a
better approach please let me know!
protected void Page_Load(Object sender, EventArgs e)
{
for (Int16 i = 1; i <= QueryBoxCount; i++)
{
QueryBox qb = (QueryBox)LoadControl("QueryBox.ascx");
qb.AddEvent += new EventHandler(QueryBox1_AddEvent);
this.Panel1.Controls.Add(qb);
}
}
protected void QueryBox1_AddEvent(Object sender, EventArgs e)
{
QueryBoxCount++;
}
private Int16 QueryBoxCount
{
get
{
return Convert.ToInt16(this.TextBox1.Text);
}
set
{
this.TextBox1.Text = value.ToString();
}
}
Thanks!