Click here to Skip to main content
15,913,587 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 
QuestionWhy do not have a 'LIKE' option in filter ? Pin
marcin.rawicki9-May-06 21:50
marcin.rawicki9-May-06 21:50 
Why do not have a 'LIKE' option in filter ?

podpis

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.