Thursday, January 31, 2008

ASP.NET: Binding alphabet to dropdown list

Update: Added VB code.

There may be some cases where you want a DropDownList to list all the letters in the alphabet (i.e. A - Z). Rather than add the letter individually (through using <asp:ListItem>) you can create an ArrayList and bind to that.

In your ASPX page:

<asp:DropDownList ID="Letters" DataSource='<%# Alphabet %>' runat="server" />

In your code behind. Create your Alphabet property:

private ArrayList _Alphabet;
protected ArrayList Alphabet
{
 get
 {
  if (_Alphabet == null)
  {
   _Alphabet = new ArrayList();
   for (int i = 65; i < 91; i++)
   {
    _Alphabet.Add(Convert.ToChar(i));
   }
  }
  return _Alphabet;
 }
}
Protected ReadOnly Property Alphabet() As ArrayList
 Get
  If _Alphabet Is Nothing Then
   _Alphabet = New ArrayList()
   For i As Integer = 65 To 91 - 1
    _Alphabet.Add(Convert.ToChar(i))
   Next
  End If
  Return _Alphabet
 End Get
End Property

Bind on Page_Load:

private void Page_Load(object sender, EventArgs e)
{
 if(!Page.IsPostBack)
 {
  DataBind();
 }
}
Public Sub Page_Load() Handles MyBase.Load
 If Not Page.IsPostBack Then
  DataBind()
 End If
End Sub

This will show A - Z (capitals) in the dropdown. For a - z (lower case), change 65 to 97 and 91 to 123 in Alphabet

No comments: