Click here to Skip to main content
14,981,456 members
Articles / Web Development / ASP.NET
Posted 4 Sep 2005


89 bookmarked

Creating a Multicolumn Combo Box in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.62/5 (17 votes)
29 Sep 20057 min read
Creating a multicolumn combo box in ASP.NET.


Previously I came across a requirement to provide a functionality of something similar to a traditional combo box (found in Windows Forms) and a sort of multicolumn combo box in ASP.NET. I searched a lot on the net but found nothing suitable for my requirements. So, I decided to write my own control from scratch and here is what I call a multicolumn combo box. It is a combo box but with multiple columns and a textbox. You can search a particular row by typing the key column value in the textbox.

The snap below shows the working of the multicolumn combo box. The first column is the key column on which we base our search. In this case it is the Item Code. When I type 9 in the textbox it shows all entries having item code starting with digit 9, and when I move my mouse over any item, for example, over an entry having item code 93, then the textbox reflects the current item code. The Search intellisense automatically opens when you type data in the search textbox. You can explicitly open Search intellisense by clicking the button on the right side of the search textbox.

Image 1

Image 2

When the search textbox is empty and you explicitly click the button then all items will be shown as you can see in the snap below. The main objective is that the user can see the data.

Image 3

A Care to be taken! When using

When using the multicolumn combo box, remove z-index of all the controls which lie in the height of the Search intellisense. Care also need to be taken when the DropdownList control lies within the height of the Search intellisense. DropDownList resides always on top irrespective of what z-index you set. That’s how the DropDownList is implemented in Windows. In the sample provided, I simulate the same action. I use two dropdown lists below the multi column combo box and hide them through the ControlsToHide property of the multi column combo box.

  <cc1:HiddenControl ControlId="DropDownList1"></cc1:HiddenControl>
  <cc1:HiddenControl ControlId="DropDownList2"></cc1:HiddenControl>

Thanks to this property, both DropDownList1 and DropDownList2 will be invisible when the multicolumn combo box is shown.

You can set this property using a collection editor which I provided in design mode.

Image 4

You have to do this step only if you have the drop down list within the height. (Text box and other controls are fine. Although, I have provided a generic model, if any control disturbs you, shoot that control out of the game by mentioning its ID!) It’s not a bug but the way the DropdownList control is implemented. I have cured this bug in my control. You can see many sites having this common bug. If you don’t do this step, you will see an output like this:

Image 5


  • Columns

    The columns to be shown in the multicolumn combo box list. Remember that the key column should be the first column in the multicolumn combo box otherwise the multicolumn combo box will fire a JavaScript error. You can change this behavior by playing with my provided JavaScript source. Moreover, only one key column is allowed. Otherwise an exception of Only one key column is allowed is thrown.

      <cc1:Column HeaderText="Item Code" KeyColumn="True" 
               DataField="PKID" ColumnWidth="10%"></cc1:Column>
      <cc1:Column HeaderText="Item Name" KeyColumn="False" 
               DataField="Name" ColumnWidth="80%"></cc1:Column>
      <cc1:Column HeaderText="UnitCost" KeyColumn="False" 
               DataField="UnitCost" ColumnWidth="10%"></cc1:Column>

    You can set this property from the Columns property collection editor.

    Image 6

  • AutoPostBack

    This property indicates whether to fire postback when the item in the multicolumn combo box is clicked or not. If this is true it fires an event of RowSelectionChanged which is captured in the aspx page like that:

    In my sample example, I have captured the auto postback event by writing code like this:

    txtName.Text = args.Cells[1].ToString();//item name column

    You can successively get the values of cells by indexing the Cells attribute because it uses the ArrayList class. For example:

    args.Cells[0].ToString();//item code
    args.Cells[1].ToString();//item name
    args.Cells[2].ToString();//unit cost
  • ItemMouseOverColor

    The color to use when the mouse moves on the items.

  • GridLinesColor

    The grid lines color of the search grid.

  • DownArrowButtonHeight

    The height of the down arrow button.

  • DownArrowButtonWidth

    The down arrow button width.

  • ValidatorErrorMessage

    The error message to be shown if no data is entered into the search textbox.

  • ValidatorText

    The text of the validator.

  • ValidatorDisplayStyle

    How the validator is rendered on the page.

  • ValidatorEnabled

    If you want to use required field validation on the search text box then enable it by making this true, otherwise false.

  • ValidatorTooltip

    The tool tip to be shown in the validator.

  • ComboBoxListHeight

    The height of the intellisense.

  • ComboBoxListWidth

    The width of the intellisense.

  • TextBoxWidth

    The width of the search data text box.

  • ValidatorCSS

    The CSS class of the required validator.

  • HeaderCSS

    The CSS class of the grid header.

  • ItemsCSS

    The CSS class of grid items.

  • DownArrowButtonCSS

    The CSS class of the down arrow button.

  • TextBoxCSS

    The CSS class of the search data text box.

  • HorizontalScrolling

    Whether to use horizontal scrolling or not.

  • VerticalScrolling

    Whether to use vertical scrolling or not.

  • ControlsToHide

    The control IDs of all those controls which might appear on top of the multicolumn combo box (for example, the DropDownList control). You can specify the IDs of all those controls using this property.

      <cc1:HiddenControl ControlId="DropDownList1"></cc1:HiddenControl>
      <cc1:HiddenControl ControlId="DropDownList2"></cc1:HiddenControl>

Data Validation Support

The multicolumn combo box internally uses the RequiredFieldValidator for validating data. You can enable or disable the validation by setting the validator properties. By default, the validation is disabled.

Image 7

When you click the Post button, you will see that the validation will be in action as shown below:

Image 8

How the multicolumn combo box works

The multicolumn combo box is a composite server control which creates a child server control in its CreateChildControls() method. This method notifies the server control to create any child control contained in it. There are two key tasks that you must perform when implementing a composite control:

  • Override the CreateChildControl method to instantiate child controls, initialize them and add them to the parent's controls hierarchy.
  • Implement the INamingContainer interface, which creates a new naming scope under your control.
Public Class MultiColumnComboBox _
       Inherits System.Web.UI.WebControls.WebControl _
       Implements INamingContainer

Now let’s discuss what is a naming scope? This concept is similar to the concept of namespaces in C++ and C#. For e.g., in the .NET Framework, the DataSet class lives in the System.Data namespace. You can’t access it directly without referring the System.Data namespace. The same rule applies to the multicolumn combo box and all composite server controls. For example, when the multicolumn combo box search text box renders on your browser, it generates the client ID like MultiColumnComboBox1:txtData. This ID tells that txtData lives within the scope of MultiColumnComboBox1 which is the ID of the parent server control.

You don’t need to generate this ID because INamingContainer does this for you automatically. When implementing this interface it creates a new naming scope for server controls and generates a unique ID for all child controls. So if you are using two instances of the multicolumn combo box on your aspx page, you will encounter something like:


Try removing the INamingContainer interface and observe its effect.

Now comes the CreateChildControl() method. In it I have created all my child controls. The line Controls.Clear() ensures that multiple copies of child controls are not added to the Controls collection of the server control. The rest is very much self explanatory.


''----Data Text box
With txtData
    .ID = "txtData"

    If Not Me.ViewState("TextBoxWidth") Is Nothing Then
        .Width = Me.ViewState("TextBoxWidth")
    End If

    If Not Me.ViewState("TextBoxCSS") Is Nothing Then
        .CssClass = Me.ViewState("TextBoxCSS")
    End If
End With

''---Down Arrow Button
btnDownArrow = New HtmlInputButton

With btnDownArrow

    .ID = "btnDownArrow"

    If Not Me.ViewState("DownArrowButtonWidth") Is Nothing Then
        .Style("Width") = Me.ViewState("DownArrowButtonWidth").ToString()
    End If

    If Not Me.ViewState("DownArrowButtonHeight") Is Nothing Then
        .Style("height") = Me.ViewState("DownArrowButtonHeight").ToString()
    End If

    If Not Me.ViewState("DownArrowButtonCSS") Is Nothing Then
        .Attributes("class") = Me.ViewState("DownArrowButtonCSS")
    End If
End With

''----Required Field Validator
If Not Me.ViewState("ValidatorEnabled") Is Nothing AndAlso _
    Me.ViewState("ValidatorEnabled") = True Then

    rfData = New RequiredFieldValidator

    With rfData
        .ControlToValidate = txtData.ID

        If Me.ViewState("ValidatorErrorMessage") Is Nothing Then
          .ErrorMessage = "Please Enter Data"
          .ErrorMessage = Me.ViewState("ValidatorErrorMessage")
        End If

        If Me.ViewState("ValidatorText") Is Nothing Then
          .Text = "*"
          .Text = Me.ViewState("ValidatorText")
        End If

        If Not Me.ViewState("ValidatorDisplayStyle") Is Nothing Then
          .Display = Me.ViewState("ValidatorDisplayStyle")
          .Display = ValidatorDisplay.None
        End If

        If Not Me.ViewState("ValidatorCSS") Is Nothing Then
          .CssClass = Me.ViewState("ValidatorCSS")
        End If
     End With
End If

''----Data Grid-----
dgSearch = New DataGrid

With dgSearch
      .ID = "dgSearch"
      .BorderWidth = New Unit(1)
      .GridLines = GridLines.Both
      .Width = New Unit("100%")

      If Not Me.ViewState("HeaderCSS") Is Nothing Then
        .HeaderStyle.CssClass = Me.ViewState("HeaderCSS")
      End If

      If Not Me.ViewState("ItemsCSS") Is Nothing Then
        .ItemStyle.CssClass = Me.ViewState("ItemsCSS")
      End If

      If Not Me.ViewState("GridLinesColor") Is Nothing Then
        .BorderColor = Me.ViewState("GridLinesColor")
        .BorderColor = Color.Black
      End If
End With

The later part of the code is a wild beast for most of the developers. Now let's eat this beast. I programmatically create dynamic template columns for the ASP.NET DataGrid. Normally we set template columns in design mode but in this case we create dynamic template columns for the ASP.NET DataGrid. When programmatically creating, you should implement the ITemplate interface like this:

Friend Class SearchGridTemplateColumn _
     Implements ITemplate

In the instantiation method I add the link button to the control hierarchy. The next thing is to bind the link button with the data source. For this purpose, I do this:

AddHandler lk.DataBinding, AddressOf DataBind

What I am doing here is setting the event handler of the DataBinding event of the LinkButton. This is called when you write dgSearch.DataBind() which in turn calls the DataBinding events of all child controls.

Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) _
                      Implements System.Web.UI.ITemplate.InstantiateIn

    Dim lk As LinkButton

    Select Case templateType
      Case ListItemType.Header
      Case ListItemType.Footer
      Case ListItemType.Item
          lk = New LinkButton
          AddHandler lk.DataBinding, AddressOf DataBind
          lk.ID = ctrlId
          'lkSelect.CommandName = "Select"
    End Select
End Sub

Now comes a more nasty part of the code. Take it another way that I am doing dynamic coding for statements like <%# DataBinder.Eval(Container.DataItem,”MyColumn”)%>. Whenever data is displayed (for example, in a DataGrid control), only one version of each row can be displayed. The displayed row is a DataRowView. In the source code below, I am getting the NamingContainer of the LinkButton with the statement CType(lk.NamingContainer, DataGridItem) which is an instance of DataGridItem. I am rendering the LinkButton in each row of the DataGrid and in the rendering process I need to know about every LinkButton. The variable dgi (dgi is present in the source code below) gives me a single item of the DataGrid and with it I refer an individual item of the data source of DataGrid. The sub statement Row.Item(Me.columnName) actually refers to the value of that row which is rendered in each column of the DataGrid.

Protected Sub DataBind(ByVal sender As Object, ByVal e As EventArgs)
    Dim lk As LinkButton
    lk = CType(sender, LinkButton)
    Dim dgi As DataGridItem
    dgi = CType(lk.NamingContainer, DataGridItem)
    lk.Text = CType(CType(dgi.DataItem, _
              DataRowView).Row.Item(Me.columnName), String)
End Sub

Now we come back to the CreateChildControls() method. Whenever adding template columns programmatically in the DataGrid, always create an instance of the TemplateColumn class.

    Dim enmDataSource As IEnumerator = dtSource.GetList().GetEnumerator()
    Dim enmColumns As IEnumerator = Columns.GetEnumerator
    Dim tc As TemplateColumn
    Dim bc As BoundColumn
    Dim col As Column
    Dim keyColCount As Integer = 0

    While enmColumns.MoveNext
        If keyColCount > 1 Then
            Throw New Exception("Only one key column is allowd")
        End If

        col = CType(enmColumns.Current, Column)
        Dim lkColId As String

        If Not col.KeyColumn Then
            'bc = New BoundColumn
            'bc.DataField = col.DataField
            'bc.HeaderText = col.HeaderText
            'bc.HeaderStyle.Wrap = False
            'If col.ColumnWidth.ToString().Length > 0 Then
                '  bc.ItemStyle.Width = col.ColumnWidth
            'End If

            lkColId = "lk" & col.DataField

            tc = New TemplateColumn
            tc.ItemTemplate = _
               New SearchGridTemplateColumn(ListItemType.Item, _
               col.DataField, lkColId)
            tc.HeaderText = col.HeaderText
            tc.HeaderStyle.Wrap = False

            If col.ColumnWidth.ToString().Length > 0 Then
                tc.ItemStyle.Width = col.ColumnWidth
            End If

            tc = New TemplateColumn
            tc.ItemTemplate = _
               New SearchGridTemplateColumn(ListItemType.Item, _
            tc.HeaderText = col.HeaderText
            tc.HeaderStyle.Wrap = False

            If col.ColumnWidth.ToString().Length > 0 Then
                tc.ItemStyle.Width = col.ColumnWidth
            End If

            keyColCount += 1
        End If
    End While

    dgSearch.AutoGenerateColumns = False
    dgSearch.DataSource = dtSource
End If


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Tahir 111
Software Developer (Senior)
Pakistan Pakistan
I love Karachi specially in the weather when there is no sun shine.I have masters degree in Computer Scince from University of Karachi(htpp:// not playing with technology I sleep a lot and don't want from any one to even bother me!You, should't event think about that!!!!
I love my mother and she is the ultimate goal of my life.

Comments and Discussions

QuestionDropDown List Pin
AyeNaingKye16-Sep-12 8:19
MemberAyeNaingKye16-Sep-12 8:19 
Generaldatabinding too slow Pin
Member 273200721-Oct-10 2:35
MemberMember 273200721-Oct-10 2:35 
QuestionVersion for .NET framework 2.0 and up? Pin
dima195426-Apr-10 2:24
Memberdima195426-Apr-10 2:24 
QuestionIs there a way to add a new option to the combo box? Pin
cgu200324-Feb-09 8:36
Membercgu200324-Feb-09 8:36 
QuestionSearch is not working Pin
Member 42451263-Feb-09 23:51
MemberMember 42451263-Feb-09 23:51 
AnswerRe: Search is not working Pin
Tahir 1116-Feb-09 1:23
MemberTahir 1116-Feb-09 1:23 
GeneralRe: Search is not working Pin
Member 424512611-Feb-09 19:59
MemberMember 424512611-Feb-09 19:59 
GeneralRe: Search is not working Pin
Tahir 11123-Feb-09 1:38
MemberTahir 11123-Feb-09 1:38 
GeneralRe: Search is not working Pin
Member 424512625-Feb-09 1:23
MemberMember 424512625-Feb-09 1:23 
GeneralRe: Search is not working Pin
Member 857917511-Feb-14 23:10
MemberMember 857917511-Feb-14 23:10 
Generaltutorial please Pin
darkdusky27-Nov-08 22:53
Memberdarkdusky27-Nov-08 22:53 
Generaldropdown list item hiding behain another control Pin
Member 44307269-Oct-08 6:38
MemberMember 44307269-Oct-08 6:38 
GeneralRe: dropdown list item hiding behain another control Pin
Tahir 11110-Nov-08 2:17
MemberTahir 11110-Nov-08 2:17 
QuestionUnable To Create Columns thro Coding Pin
VijaySofist6-Mar-08 0:16
MemberVijaySofist6-Mar-08 0:16 
GeneralUsing MCCB in .NET 2005 Pin
god@tutopia.com27-Feb-08 6:51
Membergod@tutopia.com27-Feb-08 6:51 
Generaladd Text direction to colums Pin
Ghalib Ghuneim17-Jan-08 13:53
MemberGhalib Ghuneim17-Jan-08 13:53 
GeneralRe: Another way to do so Pin
Ghalib Ghuneim17-Jan-08 13:57
MemberGhalib Ghuneim17-Jan-08 13:57 
QuestionHow to change color of Dropdownlist border (IE) Pin
Tran Huynh Long25-Jul-07 15:47
MemberTran Huynh Long25-Jul-07 15:47 
QuestionTo fetch data from mccbSubItem ddl(ddl whose postback= false) Pin
Jai Prakash Singh9-Jul-07 21:24
MemberJai Prakash Singh9-Jul-07 21:24 
GeneralSearch Function is Not Working Pin
Wiselyy736-Jul-07 12:52
MemberWiselyy736-Jul-07 12:52 
QuestionDrop-Down issue... Pin
jcruz111111-Jun-07 10:41
Memberjcruz111111-Jun-07 10:41 
GeneralJScript Error Pin
jcruz1111125-May-07 9:14
Memberjcruz1111125-May-07 9:14 
GeneralRe: JScript Error Pin
Tahir 11128-May-07 19:36
MemberTahir 11128-May-07 19:36 
GeneralRe: JScript Error Pin
jcruz1111130-May-07 9:42
Memberjcruz1111130-May-07 9:42 
Generalgr8 Pin
qumer1015-May-07 0:19
Memberqumer1015-May-07 0:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.