Hello all,
I have for two days now been trying to debug what appears to be a serious logical error in my code, now I think I need to make it public. I am working on a dynamically loaded user control, this usercontrol has two dropdownlists, followed by textboxes.The second dropdownlist is populated based on the selectedindex of the first dropdwonlist.
What I do is that, when the selectedindex of the first dropdownlist changes, I clear the items in the second list, then populate it.based on the selected index of dropdownlistbox.
Now the textboxes are all set to visibility=false. This is because the textboxes to show will depend on the selected index of the second dropdownlist box. The problem is that each time I select an item from the second drop downlistbox, the selected index of the second drop that listbox (this determines the textboxes to reveal) shows -1, instead of the actual selected index of the dropdownlist box, which I expect to be 0, 1,2 etc. and this courses the selected index of the second listbox to always reset back to the first item, causing the textboxes to be revealed wrongly. Idont know if am clear enuff?
Both listboxes are in ajax update panels.

Here a portion of my code if u would like to see:
//This is the first listbox that Loads the second listbox

protected void ListBoxProjects_SelectedIndexChanged(object sender, EventArgs e)
{
//Clear second listbox
ListBoxSources.Items.Clear();
//populate second listbox
LoadControlByProject();

}

//This is the method that loads the second list box, called in selectedIndexChanged above
protected void LoadControlByProject()
{
//Clear second listbox
//ListBoxSources.Items.Clear();

//Call method that returns linq quert result
foreach (var i in ControlLoader.GetSource(lstProjectsId.ElementAt(ListBoxProjects.SelectedIndex)))
{
// ddlSource.Items.Add(i.SourceName);
ListBoxSources.Items.Add(i.SourceName);

}
}

//This is the selectedIndex_changed of the second list box

protected void ListBoxSources_SelectedIndexChanged(object sender, EventArgs e)
{

//This sets a static int that will hold the selected index
lstSelectIndex = ListBoxSources.SelectedIndex;

//This sets the visibility of my textboxes
ToggleControls();
//Clear ListBoxSources
ListBoxSources.Items.Clear();
//This is meant to populate the second listbox again, paasing the
//The selected index as a parameter, so that the selected item
// remains selected (custom method)
LoadControlByProject(lstSelectIndex);

}

Any hint appreciated, thanks

Dani AI

Generated

A common root cause for a dropdown reporting SelectedIndex = -1 in a dynamically loaded user control is lifecycle/viewstate ordering rather than the ListBox API itself. is right to stress a stable ID and recreating the control each postback, but that must happen early enough in the page lifecycle (typically Page_Init/OnInit) so ASP.NET can restore viewstate and wire events. has already checked IDs, so the next things to verify are when the control is rebuilt and how selection state is being stored (static fields are risky for per-user state).

Concrete guidance and patterns that work reliably:

  • Recreate the user control on every postback in Page_Init (same ID and same place in the control tree). Doing it later (Page_Load) is often too late for viewstate/restoration.
  • Inside the user control, bind list data only when appropriate (usually on !IsPostBack). If a list must be rebound because the first dropdown changed, preserve the previously selected value and reapply it after DataBind.
  • Do not use static fields for per-request/per-user state. Use ViewState, ControlState, or Session instead.

Example pattern to preserve selection (store index in ViewState and restore after binding):

private int SelectedSourceIndex
{
    get { return (int)(ViewState["SelectedSourceIndex"] ?? -1); }
    set { ViewState["SelectedSourceIndex"] = value; }
}

protected void BindSources(int projectId, int preserveIndex = -1)
{
    var items = ControlLoader.GetSource(projectId).ToList();
    ListBoxSources.DataSource = items;
    ListBoxSources.DataTextField = "SourceName";
    ListBoxSources.DataValueField = "SourceId"; // optional
    ListBoxSources.DataBind();
    if (preserveIndex >= 0 && preserveIndex < ListBoxSources.Items.Count)
        ListBoxSources.SelectedIndex = preserveIndex;
}

Quick checklist: recreate the UC in Page_Init, remove static storage for selection, verify AutoPostBack and UpdatePanel triggers, avoid rebinding before reading SelectedIndex, and use ViewState/SelectedValue to restore selection after a DataBind. These steps address the typical causes that produce a -1 SelectedIndex for dynamically loaded controls.

Recommended Answers

All 2 Replies

Hello ykel,

I guess you are using a placeholder to load control.

As you say that you get a value of -1 instead of selected value, it means your ddl control get lost while rendering. To solve this do the followings
1)Please check your UC is maintained in every post back.
2) Now try adding ID for the control you load in placeholder.

Dim myTestUc As Control = LoadControl("myTestUc.ascx")
myTestUc.ID = "myTestUc"
phContainer.Controls.Add(myTestUc)

Hope this works
Thanks

Thanks for the reply, I have had code in the code behind of the parent page that does that already, but the problem still perisists...Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.