Load Controls from Event?

  • Thread starter Thread starter justsome_newbie
  • Start date Start date
J

justsome_newbie

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!
 
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!
 
Wow, that's pretty easy!

Thanks!

No problem at all, Instead using TextBox to store the value between postbacks
it would be better to use viewstate, i.e.:

protected int QueryBoxCount
{
get
{
object value = ViewState["QueryBoxCount"];
return value == null ? 1 /* i'm quessing you're displaying one Query box
by default */ : (int) value;
}
set
{
ViewState["QueryBoxCount"] = value;
}
}

Done.
--
Milosz


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?


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!
 
Back
Top