Posts Tagged ‘dropdown’

Creating a Dropdown in HTML

This is a quick tutorial on creating a dropdown in HTML. The example below has a name of myName and an id of myId. The main difference between the id and name is that the id is the identifier as used by javascript. On the other hand, name is the value recognized by form postbacks.

First, the working example:

Next, the example code:

<select id="myId" name="myName">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

Access Controls Defined in the Master Page

When you use a content page based on a previously created master page, there is sometimes a want to access attributes of control defined in the master page, such as a label, hyperlink, or dropdownlist. By default, there is no way to easy way to access the those controls. However, using the FindControl function will allow access to those controls. First part of the example is the basic master page code:

<html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
      <title>Accessing Master Page Controls</title>
      <asp:ContentPlaceHolder ID="head" runat="server">
      </asp:ContentPlaceHolder>
   </head>
   <body>
      <form id="form1" runat="server">
         <div>
            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>
            <asp:Label ID="lblUserName" runat="server" Text="Victor Chen"></asp:Label>
         </div>
      </form>
   </body>
</html>

Next, is a relevant snippet from the content page’s code behind file that will access a label defined earlier in the master page.

public partial class WebForm2 : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      String username = ((Label)Master.FindControl("lblUserName")).Text;
   }
}

The Master property listed in red will access the master page as defined in the <%@ Page MasterPageFile> property defined in the content page.

The FindControl function of the Master property takes one string input. The string input is the id of the control defined in the master page. In this case, the label id in the master page is defined as lblUserName.

Finally, the FindControl function returns an object, so we must cast the object back to a Label. Once back to a label, the text of the label can be extracted by accessing the Text property.