Click here to Skip to main content
15,891,864 members
Articles / Web Development / ASP.NET
Article

Filter Items in the Dropdown control after DataBinding

Rate me:
Please Sign up or sign in to vote.
2.20/5 (4 votes)
7 May 20062 min read 75.2K   1.5K   19   2
By default all items in the datasource are binded to the dropdownlist control;Using this control,we can filter datasource items.

Introduction

Sometimes requirement may come to bind some of the items present in the datasource (like dataset) to the dropdown control. By default all items in the datasource will be shown.

Assume we have one web form; with mutliple dropdown controls (dropdownlist1,dropdownlist2,dropdownlist3..) and 2 database tables category and values;  One to Many relationship exists between category and values tables.

Category table

CREATE TABLE [dbo].[dropdownCategory]

( [CategoryID] [int] NOT NULL,

  [Name] [varchar](50) NOT NULL,

  [Description] [varchar](255) NULL, CONSTRAINT [Category_PK] PRIMARY KEY CLUSTERED ( [CategoryID] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

CREATE TABLE [dbo].[DropdownValues]

( [dropdownValuesID] [int] IDENTITY(1,1) NOT NULL,

  [CategoryID] [int] NOT NULL,

  [Value] [varchar](50) NOT NULL,

  [Code] [varchar](50) NOT NULL ,

  CONSTRAINT [DropdownValues_PK] PRIMARY KEY CLUSTERED ( [dropdownValuesID] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

ALTER TABLE [dbo].[dropdownValues] WITH CHECK ADD CONSTRAINT [dropdownCategory_dropdownValues_FK1] FOREIGN KEY([CategoryID]) REFERENCES [dbo].[dropdownCategory] (CategoryID)

 Dropdown category Table

categoryIdName
1India
2USA
3Australia

Dropdown values Table

dropdownvaluesIdcategoryIdvaluecode
11AndhraPradeshAP
21TamilnaduTN
32South CarolinaSC
42TennesseTN
53VictoriaVic
63New South WalesNSW

Say we have 3 dropdowns on the form;dropdownlist1 should be populated with states in India,dropdownlist2 with states in USA and dropdownlist3 with states in australia. Using a single stored procedure fetch all dropdown values in to a dataset and bind it to the dropdown controls.

ddlIndia.DataTextField = "value"; ddlIndia.DataValueField = "code";

ddlIndia.datasource = dsDropdownValues; ddlIndia.databind();

ddlUSA.DataTextField = "value"; ddlUSA.DataValueField = "code";

ddlUSA.datasource = dsDropdownValues; ddlUSA.databind();

ddlAustralia.DataTextField = "value"; ddlAustralia.DataValueField = "code";

ddlAustralia.datasource = dsDropdownValues; ddlAustralia.databind();

Now we need to filter the items in the dataset;to populate the items in the dropdownlists accordingly.

Using the code

I added 2 properties(FilterBy and ColumnName) to the asp.net dropdownlist control and overided the "PerformDataBinding" method to filter the items in the datasource.

Few more properties EmptyDataText and UIFriendlyText are added to the custom dropdown list.The "emptydatatext" property is same as the "emptydatatext' property of gridview.

To make dropdownlist user friendly, normally we insert user friendly text as the top item in the dropdownlist.UserFriendlyText property value is displayed as the first item in the dropdownlist.

[ToolboxData("<{0}:CustomDropDownList runat="server"><P></{0}:CustomDropDownList></P>")]
public class CustomDropDownList : DropDownList,INamingContainer
{
    [Category("Data")]    
    [DefaultValue("")]
    [Localizable(true)]    
    public string FilterValue
    { 
        get 
        {
            object o = ViewState["FilterValue"]; return ((o == null) ? String.Empty : (string)o); 
        }
        set 
        { 
            ViewState["FilterValue"] = value; 
        } 
    } 
C#
<Bindable(true)>
[Category("Data")]
[DefaultValue("")]
[Localizable(true)]
public string    ColumnName
{
    get
    {
        object o = ViewState["columnName"]; return ((o == null) ? String.Empty :
        (string)o);
    }
    set
    {
        ViewState["columnName"] = value;
    }
}
protected override void <CODE>PerformDataBinding</CODE>(IEnumerable dataSource)
   {
       DataView dvSource = null;
       string sDataValueField = ((System.Web.UI.WebControls.ListControl)(this)).DataValueField;
       string sDataTextField = ((System.Web.UI.WebControls.ListControl)(this)).DataTextField;
       string sFilterExpression = string.Empty;
       if (dataSource != null)
       {
           dvSource = (DataView)dataSource;
           if (dvSource.Table.Columns.Contains(sDataTextField) && dvSource.Table.Columns.Contains(sDataValueField))
           {
               DataRow dr = dvSource.Table.NewRow();
               dr[sDataValueField] = "-1";
               if (dvSource.Table.Rows.Count == 0)
               {
                   dr[sDataTextField] = EmptyDataText;
                   dvSource.Table.Rows.InsertAt(dr, 0);//as first item
                   sFilterExpression = sDataValueField + " = '" + -1 + "'";
               }
               else if (UIFriendlyText != string.Empty)
               {
                   dr[sDataTextField] = UIFriendlyText;
                   dvSource.Table.Rows.InsertAt(dr, 0);//as first item
                   sFilterExpression = sDataValueField + " = '" + -1 + "'";
               }
           }

           if (ColumnName != string.Empty && FilterValue!= string.Empty)
           {
               if (sFilterExpression.Length > 0)
               {
                   sFilterExpression += " OR ";
               }
               sFilterExpression += ColumnName + " = '" + FilterValue+ "'";
           }
           dvSource.RowFilter = sFilterExpression;
       }
       base.PerformDataBinding(dvSource);
   }

Usage of the control:

ddlIndia.EmptyDataText = "No Data Items";
ddlIndia.DataSource = dsDropdownValues;
ddlIndia.ColumnName = "CategoryID";
ddlIndia.FilterValue= "1";
ddlIndia.DataBind();

ddlUSA.UIFriendlyText = "Select State";
ddlUSA.DataSource = dsDropdownValues;
ddlUSA.ColumnName = "CategoryID";
ddlUSA.FilterValue= "2";
ddlUSA.DataBind();

 

Points of Interest

In the same way we can customize the other databound controls.

License

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


Written By
Web Developer
United States United States
I have nearly 4 years of experience in microsoft technologies;working as Software consultant in US.Now focusing on Enterprise Application Integration.

Comments and Discussions

 
General[My vote of 1] Database specific. Should use <asp:XmlDataSource ID="SqlDataSource1" runat="server"> [modified] Pin
TamusRoyce6-Mar-11 17:09
TamusRoyce6-Mar-11 17:09 
It would be nice if <asp:XmlDataSource ID="SqlDataSource1" runat="server"> was used to define the datasource, and the sql server specific way was defautly commented out. I want to see the demo before I even care about firing up my server and inserting the now required tables. And then removing them once I'm finished testing.

I have your three combo boxes. But I want to filter out what gets put into them based on what is selected and what is available (an extra table).

dropdownvaluesId    categoryId    value           code

1                   1             AndhraPradesh   AP
2                   1             Tamilnadu       TN
3                   2             South Carolina  SC
4                   2             Tennesse        TN
5                   3             Victoria        Vic
6                   3             New South Wales NSW
7                   3             Queensland      QLD

categoryId      Name

1               India
2               USA
3               Australia

-- Available Combinations --

india_dropdownvalueId    usa_dropdownvalueId    australia_dropdownvalueId

1                        3                      5
1                        3                      6
1                        4                      7


So initially, only one item will be in ddlIndia--AndhraPradesh; two items in ddlUSA--South Carolina and Tennesse; and three items in ddlAustralia--Victoria, New South Wales, Queensland. Blank also needs to populate these dropdownlists. But I don't consider them items.

If you pick Queensland, ddlUSA needs to filter to only allow Tennesse or blank to be selected, and ddlIndia needs to filter to allow AndhraPradesh or blank to be selected (which is the default for ddlIndia).

Your example isn't really useful because it only does server-side filtering. And this could be alternatively accomplished by dividing up the SQL Query into three different queries. Or using code behind to filter and set these data-sources (using a lot less code). Functionality already exists by using a DataView off of the DataTable, and setting the filter there.

So essentially, you are tightly coupling the gui with filtering, which should really be done on the collection if it isn't being done on the client.

modified on Sunday, March 6, 2011 11:28 PM

QuestionWhy do not have a 'LIKE' option in filter ? Pin
marcin.rawicki9-May-06 21:50
marcin.rawicki9-May-06 21:50 

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.