Friday, July 13, 2007

Auto Resize Dropdown Box

Auto Resize Dropdown

Sometimes, using a built-in dropdown control does not meet your requirement. Suppose a dropdown box contains text that is longer in length than your box; therefore, the width of the dropdown will increase as the text length increases. But, an increase in the dropdown's size affects your form design. You don't have enough space on your page to fit this lengthy dropdown box. In that case, you can use this Auto Resize Dropdown box.


Create a blank solution; in the solution, add a class library; and in the class file, add the following code. This code shows that, at the time of rendering the control, with the help of a style you can maintain the initial width of your dropdown box.

Note: You must inherit WebControls.DropDownList.
Inherits WebControls.DropDownList
Protected Overrides Sub Render(ByVal writer As _
writer.Write("<div style='width:" & Me.Width.ToString & "'>")
End Sub

Full Size Image)

At the time of initialization, it will call JavaScript functions. These JavaScript functions will attach with onactivate and ondeactivate events.

Private Sub AutoSizeDropDown_Init(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Init
Dim ControlsJS As String
ControlsJS = "<script type=""text/javascript"" src=""" &
HttpRuntime.AppDomainAppVirtualPath & "/js/CustomControls.js""> _
Me.Attributes.Add("originalWidth", "")
Me.Attributes.Add("onactivate", "RearrangeDdnWidth(this)")
Me.Attributes.Add("ondeactivate", "ResetDdnWidth(this)")
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), _
"ControlsJS", ControlsJS)
End Sub

(Full Size Image)

After building the solution, add a new web site in your solution. In the default.aspx page, register your DLL with the page.

<%@ Register Assembly="AutoDropDown"
Namespace="AutoDropDown" TagPrefix="cc1" %>

After that, you can add the dropdown:

<cc1:AutoSizeDropDown runat="server"

(Full Size Image)

The complete source code is available with this article.


  • - Complete Source Code
  • No comments: