Initially Unselected DropDownList

Posted by Ricardo Peres on ASP.net Weblogs See other posts from ASP.net Weblogs or by Ricardo Peres
Published on Fri, 26 Mar 2010 11:53:02 GMT Indexed on 2010/03/26 11:53 UTC
Read the original article Hit count: 707

Filed under:
|

One of the most (IMHO) things with DropDownList is its inability to show an unselected value at load time, which is something that HTML does permit.

I decided to change the DropDownList to add this behavior. All was needed was some JavaScript and reflection. See the result for yourself:

public class CustomDropDownList : DropDownList
	{
		public CustomDropDownList()
		{
			this.InitiallyUnselected = true;
		}

		[DefaultValue(true)]
		public Boolean InitiallyUnselected
		{
			get;
			set;
		}

		protected override void OnInit(EventArgs e)
		{
			this.Page.RegisterRequiresControlState(this);

			this.Page.PreRenderComplete += this.OnPreRenderComplete;

			base.OnInit(e);
		}

		protected virtual void OnPreRenderComplete(Object sender, EventArgs args)
		{
			FieldInfo cachedSelectedValue = typeof(ListControl).GetField("cachedSelectedValue", BindingFlags.NonPublic | BindingFlags.Instance);
			
			if (String.IsNullOrEmpty(cachedSelectedValue.GetValue(this) as String) == true)
			{
				if (this.InitiallyUnselected == true)
				{
					if ((ScriptManager.GetCurrent(this.Page) != null) && (ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack == true))
					{
						ScriptManager.RegisterStartupScript(this, this.GetType(), "unselect" + this.ClientID, "$get('" + this.ClientID + "').selectedIndex = -1;", true);
					}
					else
					{
						this.Page.ClientScript.RegisterStartupScript(this.GetType(), "unselect" + this.ClientID, "$get('" + this.ClientID + "').selectedIndex = -1;", true);
					}
				}
			}
		}
	}


	


Bookmark and Share

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about ASP.NET