Select from dropdown then treeview - not holding position
I am having problems with postbacks.
I have a dropdownlist that i add items to at runtime. When i select a item in the dropbox a treeview is filled with items that have the same pID value as the object selected in the dropdownlist.
But when i select a node in the treeview everything goes back to "normal" state. The dropbox will go to selectindex -1 and the treeview disappear.
I have theese controllers in a master page if that matters.
This is my code.
public partial class Nemanet : System.Web.UI.MasterPage
{
nemanetDataContext dc = new nemanetDataContext();
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
bool reloadPeriod = true;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (reloadPeriod == true)
{
reloadPeriod = false;
var query = from n in dc.Nemanet_Navigations
where n.UserId == userGuid && n.Nav_pID == null
orderby n.Nav_Name ascending
select n;
foreach (var period in query)
{
ListItem period_listitem = new ListItem(period.Nav_Name, period.Nav_ID.ToString());
dropdown_navigation.Items.Add(period_listitem);
}
}
}
}
protected void dropdown_navigation_SelectedIndexChanged(object sender, EventArgs e)
{
treeview_Navigation.Nodes.Clear();
var query = from n in dc.Nemanet_Navigations
where n.UserId == userGuid
orderby n.Nav_Name ascending
select n;
foreach (var course in query)
{
if (course.Nav_pID.ToString() == dropdown_navigation.SelectedValue)
{
TreeNode course_node = new TreeNode(course.Nav_Name, course.Nav_ID.ToString());
course_node.NavigateUrl = "Default.aspx?navigateID=" + course.Nav_ID;
treeview_Navigation.Nodes.Add(course_node);
foreach (var chapter in query)
{
if (chapter.Nav_pID.ToString() == course_node.Value)
{
开发者_高级运维 TreeNode chapter_node = new TreeNode(chapter.Nav_Name, chapter.Nav_ID.ToString());
chapter_node.NavigateUrl = "Default.aspx?navigateID=" + chapter.Nav_ID;
course_node.ChildNodes.Add(chapter_node);
foreach (var subject in query)
{
if (subject.Nav_pID.ToString() == chapter_node.Value)
{
TreeNode subject_node = new TreeNode(subject.Nav_Name, subject.Nav_ID.ToString());
subject_node.NavigateUrl = "editor.aspx?navigateID=" + subject.Nav_ID;
chapter_node.ChildNodes.Add(subject_node);
}
}
}
}
}
}
}
}
Any dynamically added elements will be gone after any postback, so you have add all of them again after every postback (your page is rebuild from the ground using the frontpage and page load).
To avoid reloading all the data from the database, store it in the Session.
Session["items"] = query;
if(IsPostBack) foreach(var period in (Collection)Session["items"]) dropdown_navigation.Items.Add(new ListItem(period.Nav_Name, period.Nav_ID.ToString()));
精彩评论