Calendar

<<  January 2009  >>
SunMonTueWedThuFriSat
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567

View posts in large calendar

Recent posts

Recent comments

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2009

Sign in

Bind DropDownList to Enum in C#

by HyperbolicHyperbally 10/31/2007 4:37:00 PM

Since I constantly keep forgetting how to do this I'll write it down here and then I'll know where to find it just like my  Regular Expressions post.

In web development you often need to allow the customer/user to choose options and often they'll have need to select a type of something. An example would be to choose what type of account and on the back end the accounts types are stored in and enum. Since I don't want to change every page where I've got a control with type information when I add or remove an item from the enum, it's best to just bind the control to the enum in the first place.

  //Create an enum enum AccountType
  {
    Checking,
    Savings
  }
  //Assume we've got some methods on a page.
  protected void Page_Load(object o, EventArgs e)
  {
    if(!Page.IsPostBack)//Only do it on the intitial load.
    {
      //DropDownList ddl will hold our data
      ddl.DataSource = Enum.GetNames(typeof(AccountType));
      ddl.DataBind();
    }
  }
  protected void ddl_SelectedIndexChanged(object o,EventArgs e)
  {
    //Now get the selected Value out of the control and back into an enum
    AccountType acc = (AccountType)Enum.Parse(ddl.SelectedValue);
    //Do stuff
   }
source: How to Bind Enum Types to bindable Controls in ASP.Net....  on Geeks with Blogs
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Code

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

1/6/2009 5:12:43 PM

Powered by BlogEngine.NET 1.3.0.0