This project is read-only.

Dropdown extension methods

When working with databound dropdown lists, you often need to add a default value. With the InsertDefault() extension (and overloads) the pattern for a setter typically will look like this:

public List<Users> AllowedUsers
{
    set
    {
          ddlUsers.DataSource = value;
          ddlUsers.ValueField = "Id";
          ddlUsers.TextField = "AccountName";
          ddlUsers.DataBind();
          ddlUsers.InsertDefault("-- none --");
    }
}


The InsertDefault method will insert a ListItem with an empty value. To retrieve the ID of the selected user simply use the SelectedValueAsIntegerNullable(), which will do all the tryParsing stuff for you.

public int? SelectedUser
{
   get
   {
       return ddlUsers.SelectedValueAsIntegerNullable();
   }
}


The are some other variants, e.g. for working with Guid's.

DropDownList ddlItems;


ddlItems.InsertDefault("-- please select a value --");

int value1 = ddlItems.SelectedValueAsInteger();
int? value2 = ddlItems.SelectedValueAsIntegerNullable();


Guid value3 = ddlItems.SelectedValue();
Guid? value4 = ddlItems.SelectedValueAsGuidNullable();


Last edited Oct 11, 2011 at 11:07 AM by drblame, version 2

Comments

No comments yet.