Groups | Blog | Home
all groups > asp.net webcontrols > february 2005 >

asp.net webcontrols : Dynamically adding DropDownList - if I set ID also, I lose PostBack EventHandler


Wilco Bauwer
2/27/2005 2:07:03 AM
How are you adding those controls? Are you adding them manually to the
control hierarchy? Or are you databinding it against, for example, a
Repeater?

It is important that after a postback, the controls are re-added
properly. In cases where you have a dynamic number of controls you'd
like to add, it makes sense to databind a control and display the
controls inside that databound control (e.g. a Repeater). If you then
postback, your control will still be there (the Repeater takes care of
re-creating its children).

--
- Wilco Bauwer
Blog & Custom Controls @ http://wilcoding.xs4all.nl
Wilco Bauwer
2/27/2005 4:12:53 AM
Take a look at http://wilcoding.xs4all.nl/Wilco/View.aspx?NewsID=147
aswell.

--
- Wilco Bauwer
Blog & Custom Controls @ http://wilcoding.xs4all.nl
DotNetJunky
2/27/2005 6:39:48 AM
I have built a control that runs an on-line help system. Depending on the
category you selected via dropdownlist, it goes out and gets the child
subcategories, and if there are any, adds a new dropdownlist to the screen
for selection. This continues until there are no children, and then it
checks for a help article list based on that last selection and displays
actual articles for display.

Adding the controls and getting everything displaying has worked fine so
far. the problem is when the user goes back and changes a past dropdown, i
need to account for what happens to the successive dropdowns related to that
parent.

What i decide was just to disable previously selected dropdowns, each time a
new one is added, and then add a link to "start-over" basically.

Unfortunately, i cant even loop through the dynamically added dropdownlists
on the page because if i set an ID property when they are added, i lose my
postback event!

Can anyone explain to me what is going on with that or any alternatives?

I even tried adding an "id" attribute to the dropdownlists, and then my
postback handler works again but i cannot do a page.findcontrol() on that
attribute value, because it really isn't the "ID" of it, it doesn't find it.

Thanks in advance.

- DotNetJunky

DotNetJunky
2/27/2005 11:42:08 PM
I am storing the categories posted back from the dropdowns into an arrayList
and then ViewStating the arrayList. On PostBack i check that arrayList and
re-run the routine which builds the dropDowns and adds them to the page with
their event handlers.

I am adding them manually to the control hierarchy, by simply adding a new
asp:table cell and then adding the control to it.

attached is sample test code (thrown together in an hour):

========================================================================

using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace Testing
{
/// <summary>
/// Summary description for TestDD.
/// </summary>
public class TestDD : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Table tblCategory;
protected System.Web.UI.WebControls.Label lblArticleDate;
protected System.Web.UI.WebControls.Label lblArticleTitle;
protected System.Web.UI.WebControls.Label lblArticleContent;
protected System.Web.UI.WebControls.DropDownList ddList1;
protected System.Web.UI.WebControls.LinkButton lbRestart;
protected System.Web.UI.HtmlControls.HtmlForm Form1;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!Page.IsPostBack)
{
ddList1.DataSource = GetCategories(0);
ddList1.DataBind();

//add default item
ListItem _liDefault = new ListItem("Please select Category ->","");
ddList1.Items.Insert(0,_liDefault);
ddList1.Attributes.Add("id","ddList1");

//GenerateNewDropDown(Convert.ToInt64(ddList1.SelectedValue));

System.Collections.ArrayList _CatList = new ArrayList();
System.Collections.ArrayList _PrevDDList = new ArrayList();

ViewState["CatList"] = _CatList;
ViewState["PrevDDList"] = _PrevDDList;
ViewState["ddListCount"] = 0;
}
else
{
System.Collections.ArrayList _CatList = (ArrayList)ViewState["CatList"];

for (int i = 0; i < _CatList.Count; i++)
{
GenerateNewDropDown(Convert.ToInt64(_CatList[i]));
}

//DisablePrevious(this.Page);
}
}

public DataTable GetCategories(long catid)
{
//Create Instance of Connection and Command Object
SqlConnection oConnection = new
SqlConnection(ConfigurationSettings.AppSettings.Get("ConnectionString"));
SqlDataAdapter daItems = new
SqlDataAdapter("tPortal_Help_Category_sel_List", oConnection);
//Mark the Command as a SPROC
daItems.SelectCommand.CommandType = CommandType.StoredProcedure;
//Add paramaters to SPROC
SqlParameter paramParentID = new SqlParameter("@parent_id",
SqlDbType.BigInt);
paramParentID.Value = catid;
daItems.SelectCommand.Parameters.Add(paramParentID);
//Create the DataSet
DataSet dsItems = new DataSet();
//Fill DataSet
daItems.Fill(dsItems);
//Close Connection
daItems.SelectCommand.Connection.Close();

return dsItems.Tables[0];
}

public DataTable GetArticles(long catid)
{
//Create Instance of Connection and Command Object
SqlConnection oConnection = new
SqlConnection(ConfigurationSettings.AppSettings.Get("ConnectionString"));
SqlDataAdapter daItems = new SqlDataAdapter("tPortal_Help_sel_List",
oConnection);
//Mark the Command as a SPROC
daItems.SelectCommand.CommandType = CommandType.StoredProcedure;
//Add paramaters to SPROC
SqlParameter paramParentID = new SqlParameter("@category_id",
SqlDbType.BigInt);
paramParentID.Value = catid;
daItems.SelectCommand.Parameters.Add(paramParentID);
//Create the DataSet
DataSet dsItems = new DataSet();
//Fill DataSet
daItems.Fill(dsItems);
//Close Connection
daItems.SelectCommand.Connection.Close();

return dsItems.Tables[0];
}

public DataTable GetArticle(long helpid)
{
//Create Instance of Connection and Command Object
SqlConnection oConnection = new
SqlConnection(ConfigurationSettings.AppSettings.Get("ConnectionString"));
SqlDataAdapter daItems = new SqlDataAdapter("tPortal_Help_sel_GetHelp",
oConnection);
//Mark the Command as a SPROC
daItems.SelectCommand.CommandType = CommandType.StoredProcedure;
//Add paramaters to SPROC
SqlParameter paramParentID = new SqlParameter("@help_id",
SqlDbType.BigInt);
paramParentID.Value = helpid;
daItems.SelectCommand.Parameters.Add(paramParentID);
//Create the DataSet
DataSet dsItems = new DataSet();
//Fill DataSet
daItems.Fill(dsItems);
//Close Connection
daItems.SelectCommand.Connection.Close();

return dsItems.Tables[0];
}


private void ddLists_SelectedIndexChanged(object sender, System.EventArgs
e)
{
DropDownList _ddList = (DropDownList)sender;

GenerateNewDropDown(Convert.ToInt64(_ddList.SelectedValue));
}

private void ddArticles_SelectedIndexChanged(object sender,
System.EventArgs e)
{
DropDownList _ddList = (DropDownList)sender;
if ( _ddList.SelectedIndex > 0 )
{
DataTable _dtArticle =
GetArticle(Convert.ToInt64(_ddList.SelectedValue));
if (_dtArticle.Rows.Count > 0)
{
lblArticleDate.Text =
_dtArticle.Rows[0]["date_lastupdated"].ToString();
lblArticleTitle.Text = _dtArticle.Rows[0]["help_title"].ToString();
lblArticleContent.Text =
_dtArticle.Rows[0]["help_content"].ToString();
}
}
}

private void GenerateNewDropDown(long parentid)
{

DataTable _dtCats = GetCategories(parentid);
DataTable _dtArticleList = new DataTable();
DropDownList _NewDDList = new DropDownList();
_NewDDList.AutoPostBack = true;
_NewDDList.EnableViewState = true;
_NewDDList.SelectedIndexChanged += new
System.EventHandler(this.ddLists_SelectedIndexChanged);
//_NewDDList.ID = "ddList" + Convert.ToString(CountDDLists(this.Page) +
1);
_NewDDList.Attributes.Add("id", "ddList" +
Convert.ToString(CountDDLists(this.Page) + 1));

if (_dtCats.Rows.Count > 0)
{

for (int i = 0; i < _dtCats.Rows.Count; i++)
{
ListItem _liNew = new
ListItem(_dtCats.Rows[i]["category_name"].ToString(),_dtCats.Rows[i]["id"].ToString());
_NewDDList.Items.Add(_liNew);
}

//add default item
ListItem _liDefault = new ListItem("Please select SubCategory ->","");
_NewDDList.Items.Insert(0, _liDefault);

TableCell _newCell = new TableCell();
int _newCellIndex = tblCategory.Rows[0].Cells.Add(_newCell);
tblCategory.Rows[0].Cells[_newCellIndex].Controls.Add(_NewDDList);


//GenerateNewDropDown(Convert.ToInt64(_NewDDList.SelectedValue));

System.Collections.ArrayList _CatList = (ArrayList)ViewState["CatList"];

AddThis Social Bookmark Button