Hi , i want to ask something related to this thread.
I want to add a new DropDownList to a panel only when user clicks button "Add New", and add an event handler CheckedChanged to this control.
I also want to have the viewstate of every dropdownlist i have already added in order to use it when user clicks "Submit" (another button).
I figured out that the solution is ( according to lifecycle of aspx page ) :
PageInit
if (Session["countDDL"] == null)
Session["countDDL"] = 0;
Session["countDDL"] = int.Parse(Session["countDDL"].ToString()) + 1;
for (int i = 0; i < int.Parse(Session["countDDL"].ToString()); i++)
{
DropDownList processes = new DropDownList();
ListItem lsi = new ListItem("Choose ");
processes.ID = "processes" + i.ToString();
processes.Width = 150;
processes.Items.Add(lsi);
processes.AutoPostBack = true;
FillList(processes);
processes.SelectedIndexChanged += new EventHandler(processes_SelectedIndexChanged);
pnlProcesses.Controls.Add(processes);
}
Create and fill all the dropdownlists that exist plus one more . The Viewstate works fine if the IDs are the same.
PageLoad
Session["buttonAddNewPressed"] = false;
Reset Session key.
protected void AddNewProcess_Click(object sender, ImageClickEventArgs e)
{
Session["buttonAddNewPressed"] = true;
}
protected void Page_PreRender(object sender, EventArgs e)
{
if ((bool)Session["buttonAddNewPressed"] == false)
{
pnlProcesses.Controls.RemoveAt(pnlProcesses.Controls.Count -1);
Session["countDDL"] = int.Parse(Session["countDDL"].ToString()) - 1;
}
}
If Button "Add New" didn't press i delete the last dropdownlist beacuse another event happened and decrease the session counter by one.
My question is " Can i make my code better ?" , i don't want to create and delete controls after . I decided to do this because the "Add New" Event fires between Page_Load and PreRender steps and the only way to create a control that its handlers are registered is to create before PreRender. So I create it at Init It could be in Page_Load as well and then if the button pressed i don't delete it.
Thanx in advance,
koraki_g