Initially Unselected DropDownList

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

                             

No Comments