Create a Drop Down List Populated with Pages

Here we shall demonstrate how to create a drop-down list and programmatically add all the pages under the current page to the drop down list.  The list will be populated in the code behind file along with the onSelectedIndexChanged handle.

  1. Decide where you want your drop down list and add the mark up. We shall provide a custom handler that will be called when the index changes in the drop-drop list,we have named the handler Selection_Change.  Note that the DataTextField property is set to PageName and that the DataValueField property is set to LinkURL:
        <asp:DropDownList id="MyPageList"
            AutoPostBack="true" Width="130px" 
            DataTextField="PageName" DataValueField="LinkURL"
             onSelectedIndexChanged="Selection_Change"
            runat="server">
       </asp:DropDownList>
     
  2. In the code behind in the the Page_Load event, the drop down list is populated with the sub pages of the current page:  if (!IsPostBack)
       {
         // Add a default item to the drop down list
         MyPageList.Items.Add(new ListItem("Select a page", 
         "Select a page"));

         // Create a page Collection
         PageDataCollection pdc = GetChildren
         (CurrentPage.PageLink);
         foreach (PageData page in pdc)
         {
           MyPageList.Items.Add(new ListItem(page.PageName.
           ToString(), page.PageName.ToString()));
         }
       }

  3. Here we add the handler for the event when the drop down list index is changed. We create a page collection of the the sub pages and then iterate through the list and search for the page that matches the page chosen in the drop down list.. When the page has been found we pass the page's url to the Redirect() method:
    public void Selection_Change(Object sender, EventArgs e)
    {
       PageDataCollection pdc = GetChildren(CurrentPage.PageLink);
       foreach (PageData page in pdc)
       {
         if(MyPageList.SelectedItem.Text == page.PageName)
         {
          Response.Redirect(page.LinkURL.ToString(), true);
          break;
         }
       }                                  
    }

  4. The drop-down list control should now list all the pages sub pages and when selected should navigate you to the selected page:



View and download the Example Code File 

Open Code File

 DropDownList_template.aspx code file

 

Open Code File

 DropDownList_template.aspx code file

 

Open Code File

 DropDownList_template.aspx code file

 

File that opens in a new window. If you want to download, right-click on the link and choose Save Target as... 


FeedBackbutton image
EPiTrace logger