Skip to main content

Multi-Selection Dropdown box in ASP.NET


In this post, I am planning to give an example implementation of Multi-Selection dropdown box in asp.net. This implementation provides a generalized control which can be used at any asp.net page.

I have created two project one for developing the multi selection dropdown control (MultiSelectDropdown) and a project for testing the control (MultiSelectDropdownTest).

The MultiSelectDropdown project contains dropdown control implementation, which has MultiSelectDropdown.cs, HiddenData.cs, MultiSelectDropdown.js and Default.css files. It also has image for showing dropdown icon.

Note: This implementation works only when assigning the entity collection (such as IList, Arrays etc) to the DataSource property of the control and not works for DataSet, DataReader, DataTable etc.,

The MultiSelectDropdown class contains the dropdown implementation.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
[ToolboxData("<{0}:MultiSelectDropdown runat=server></{0}:MultiSelectDropdown>")]
public class MultiSelectDropdown : DataBoundControl, INamingContainer, IPostBackDataHandler
{
    public MultiSelectDropdown() : base() {}
 
    private HtmlContainerControl divText;
    private HtmlInputHidden hiddenVal;
    private string dataTextField = string.Empty;
    private string dataValueField = string.Empty;
    private IEnumerable<string> selectedValue;
 
    [Category("Data")]
    public IEnumerable<string> SelectedValue
    {
        get
        {
            EnsureChildControls();
 
            string strValue = hiddenVal.Value;
 
            var objJavaScriptSerializer = new JavaScriptSerializer();
 
            HiddenData hiddenData = new HiddenData();
            if (hiddenVal.Value.Trim().Length > 0)
                hiddenData = objJavaScriptSerializer.Deserialize<HiddenData>(hiddenVal.Value);
            return hiddenData.SelectedValue;
        }
        set { EnsureChildControls(); selectedValue = value; }
    }
 
    [Category("Data")]
    public string DataTextField
    {
        get { EnsureChildControls(); return dataTextField; }
        set { EnsureChildControls(); dataTextField = value; }
    }
 
    [Category("Data")]
    public string DataValueField
    {
        get { EnsureChildControls(); return dataValueField; }
        set { EnsureChildControls(); dataValueField = value; }
    }
 
    protected override void OnPreRender(EventArgs e)
    {
        Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "LoadScript1", Page.ClientScript.GetWebResourceUrl(this.GetType(), "MultiSelectDropdown.Script.jquery-1.4.1.min.js"));
        Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "LoadScript2", Page.ClientScript.GetWebResourceUrl(this.GetType(), "MultiSelectDropdown.Script.MultiSelectDropdown.js"));
 
        base.OnPreRender(e);
    }
 
    protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
    {
        base.AddAttributesToRender(writer);
        if (DataTextField.Length > 0 && DataTextField.Length == 0)
            DataTextField = DataValueField;
        else if (DataTextField.Length == 0 && DataTextField.Length > 0)
            DataValueField = DataTextField;
        hiddenVal.Attributes.Add("alt", DataValueField + "," + DataTextField);
    }
 
    protected override void Render(HtmlTextWriter output)
    {
        base.Render(output);
    }
 
    protected override void CreateChildControls()
    {
        base.CreateChildControls();
 
        var styleSheetUrl = this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "MultiSelectDropdown.Style.Default.css");
        var link = new HtmlLink();
        link.Attributes["rel"] = "stylesheet";
        link.Attributes["type"] = "text/css";
        link.Attributes["href"] = styleSheetUrl;
        this.Page.Header.Controls.Add(link);
 
        this.CssClass = "dntdropdown";
 
        divText = new HtmlGenericControl("div");
        divText.Attributes.Add("class", "divText");
 
        HtmlAnchor anchor = new HtmlAnchor();
        anchor.Attributes.Add("class", "anchor");
             
        HtmlImage img = new HtmlImage();
        img.Attributes.Add("src", this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "MultiSelectDropdown.Images.normal.jpg"));
        anchor.Controls.Add(img);
 
        divText.Controls.Add(anchor);
 
        this.Controls.Add(divText);
 
        hiddenVal = new HtmlInputHidden();
        hiddenVal.Attributes.Add("id", "hiddenVal");
 
        HiddenData hiddenData = new HiddenData();
 
        System.Web.Script.Serialization.JavaScriptSerializer objSerializer =
                    new System.Web.Script.Serialization.JavaScriptSerializer();
 
        hiddenData.DataSource = objSerializer.Serialize(DataSource);
 
        System.Collections.Generic.IEnumerable<string> SelectedValue = new System.Collections.Generic.List<string>();
        hiddenData.SelectedValue = SelectedValue;
 
        hiddenVal.Value = objSerializer.Serialize(hiddenData);
        this.Controls.Add(hiddenVal);
    }
 
    #region IPostBackDataHandler Members ============================================
    /// <summary>
    /// Raise events that are needed when the control's data changes
    /// </summary>
    public void RaisePostDataChangedEvent()
    {
        // Nothing to do.  Default handlers work as long as this interface is defined
    }
 
    /// <summary>
    /// Load the values into the controls from the post-back data
    /// </summary>
    /// <param name="postDataKey"></param>
    /// <param name="postCollection"></param>
    /// <returns></returns>
    public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
    {
        return true;
    }
    #endregion
}
The MultiSelectDropdown.js script
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
$(document).ready(function () {
 
    var $container = null;
 
    $('.dntdropdown').each(function () {
        var height = $(this).outerHeight();
        $(this).closest("span").find('.anchor').css({
            height: height - 4 + "px"
        });
 
        var hiddenData = jQuery.parseJSON($(this).closest("span").find('#hiddenVal').val());
 
        $(this).closest("span").find('.divText').html("(" + hiddenData.SelectedValue.length + ") Selected" + $(this).closest("span").find('.divText').html());
 
    });
 
    dntchkBox = function () {
        var ArrSelectedValue = new Array();
        $('.divDropdown table tr td input:checked').each(function () {
            ArrSelectedValue.push($(this).val());
        });
 
        $container.find(".divText").html("(" + ArrSelectedValue.length + ") Selected" + $container.find(".divText").find("a").outerHTML());
 
        var hiddenData = jQuery.parseJSON($container.find("#hiddenVal").val());
        hiddenData.SelectedValue = ArrSelectedValue;
        $container.find("#hiddenVal").val(JSON.stringify(hiddenData));
    };
 
    $(".dntdropdown").click(function () {
 
        $container = $(this).closest("span");
 
        if ($container.find('.divDropdown').length == 0) {
            var data = $container.find("#hiddenVal").val();
 
            var dataValueField = $container.find("#hiddenVal").attr("alt").split(',')[0];
            var dataTextField = $container.find("#hiddenVal").attr("alt").split(',')[1];
 
            var HiddenData = jQuery.parseJSON(data);
 
            var arrDataSource = jQuery.parseJSON(HiddenData.DataSource);
 
            var selectedValue = new Array();
            if (HiddenData.SelectedValue.length > 0)
                selectedValue = HiddenData.SelectedValue;
 
            var divDropdown = $("<div class='divDropdown'></div>");
            var valuesdiv = $("<div></div>");
            var table = $("<table />");
 
            for (var index = 0; index < arrDataSource.length; index++) {
                var value, text;
 
                if (dataTextField.length > 0) {
                    value = arrDataSource[index][dataValueField];
                    text = arrDataSource[index][dataTextField];
                }
                else {
                    value = arrDataSource[index];
                    text = arrDataSource[index];
                }
                if (jQuery.inArray(value.toString(), selectedValue) === -1)
                    table.append("<tr><td><input name='options' onclick='dntchkBox()' type='checkbox' value='" + value + "'>" + text + "</td></tr>");
                else
                    table.append("<tr><td><input name='options' checked='checked' onclick='dntchkBox()' type='checkbox' value='" + value + "'>" + text + "</td></tr>");
            }
 
            valuesdiv.append(table);
            divDropdown.append(valuesdiv);
            $('body').append(divDropdown);
 
            var pos = $(this).position();
            var width = $(this).outerWidth();
            var height = $(this).outerHeight();
 
            var tblwidth = table.outerWidth();
            valuesdiv.css({ width: tblwidth + "px", minWidth: "100%" }).show();
 
            divDropdown.css({
                position: "absolute",
                overflow: "auto",
                textAlign: "left",
                backgroundColor: "white",
                border: "1px solid black",
                color: "black",
                maxHeight: "200px",
                width: width - 2 + "px",
                top: pos.top + height + "px",
                left: pos.left + 8 + "px"
            }).show();
        }
        else
            $container.find('.divDropdown').css({ display: "block" });
    });
    jQuery.fn.outerHTML = function (s) {
        return s ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html();
    };
    $(document).mouseup(function (e) {
        var container = $(".divDropdown");
        if (container.has(e.target).length === 0) {
            container.detach();
        }
    });
});
The Default.css stylesheet
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
.dntdropdown
{
 border:1px solid black;
 padding:0px;
 margin:0px;
 height:100%;
 cursor:pointer;
}
.divText
{
    border-right:1px solid black;
    width:100%;
    float:left;
    margin-right:20px;
}
.anchor
{
    vertical-align:middle;
    text-align:center;
    border:1px solid black;
    width:15px;
    float:right;
}
The HiddenData class is used for handling JSON string for data source and selected values.
?
1
2
3
4
5
public class HiddenData
{
    public string DataSource { get; set; }
    public IEnumerable<string> SelectedValue { get; set; }
}
Now let us test this control in the Test project.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <cc1:MultiSelectDropdown ID="MultiSelectDropdown1" runat="server" Width="150px" Height="20px" />
 
 
    <cc1:MultiSelectDropdown ID="MultiSelectDropdown2" runat="server" Width="200px" Height="20px" />
 
 
    <cc1:MultiSelectDropdown ID="MultiSelectDropdown3" runat="server" Width="100px" Height="20px" />
 
 
 
    <asp:Button ID="btnTest1" Text="Get Values of MultiSelectDropdown1" runat="server" onclick="btnTest1_Click" />
 
 
    <asp:Button ID="btnTest2" Text="Get Values of MultiSelectDropdown2" runat="server" onclick="btnTest2_Click" />
 
 
    <asp:Button ID="btnTest3" Text="Get Values of MultiSelectDropdown3" runat="server" onclick="btnTest3_Click" />
 
 
    <asp:TextBox ID="txt" Text="" runat="server" Width="700px"></asp:TextBox>
     
 
 
 
 
    <asp:DropDownList ID="ddlList" runat="server" Width="200px"></asp:DropDownList>
 
 
</asp:Content>
The Codebehind code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
protected void Page_Load(object sender, EventArgs e)
{
    MultiSelectDropdown1.DataSource = GetCategory();
    MultiSelectDropdown1.DataTextField = "CategoryName";
    MultiSelectDropdown1.DataValueField = "CategoryID";
    MultiSelectDropdown1.DataBind();
 
 
    MultiSelectDropdown2.DataSource = GetCustomer();
    MultiSelectDropdown2.DataTextField = "CustomerName";
    MultiSelectDropdown2.DataValueField = "CustomerID";
    MultiSelectDropdown2.DataBind();
 
    List<string> data = new List<string>();
    data.Add("Jan");
    data.Add("Feb");
    data.Add("Mar");
 
    ddlList.DataSource = data;
    ddlList.DataBind();
 
    MultiSelectDropdown3.DataSource = data;
    MultiSelectDropdown3.DataBind();
}
 
public IList<Category> GetCategory()
{
    SqlConnection connection = null;
 
    try
    {
        connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
 
        string strQuery = @"SELECT CategoryID, CategoryName, [Description] FROM Categories";
 
        SqlCommand command = new SqlCommand();
        command.CommandText = strQuery;
        command.Connection = connection;
 
        command.Connection.Open();
        SqlDataReader dataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
 
        IList<Category> categoryList = new List<Category>();
 
        while (dataReader.Read())
        {
            Category category = new Category();
            category.CategoryID = Convert.ToInt32(dataReader[0].ToString());
            category.CategoryName = dataReader[1].ToString();
            category.Description = dataReader[2].ToString();
 
            categoryList.Add(category);
        }
 
        connection.Close();
 
        //return
        return categoryList;
    }
    catch (Exception ex)
    {
        if (connection != null) connection.Close();
 
        // Log
        throw ex;
    }
}
public IList<Customer> GetCustomer()
{
    SqlConnection connection = null;
 
    try
    {
        connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
 
        string strQuery = @"select CustomerID, CompanyName from Customers";
 
        SqlCommand command = new SqlCommand();
        command.CommandText = strQuery;
        command.Connection = connection;
 
        command.Connection.Open();
        SqlDataReader dataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
 
        IList<Customer> customerList = new List<Customer>();
 
        while (dataReader.Read())
        {
            Customer customer = new Customer();
            customer.CustomerID = dataReader[0].ToString();
            customer.CustomerName = dataReader[1].ToString();
 
            customerList.Add(customer);
        }
 
        connection.Close();
 
        //return
        return customerList;
    }
    catch (Exception ex)
    {
        if (connection != null) connection.Close();
 
        // Log
        throw ex;
    }
}
 
protected void btnTest1_Click(object sender, EventArgs e)
{
    txt.Text = string.Join(",", MultiSelectDropdown1.SelectedValue.Select(x => x.ToString()).ToArray()); ;
}
 
protected void btnTest2_Click(object sender, EventArgs e)
{
    txt.Text = string.Join(",", MultiSelectDropdown2.SelectedValue.Select(x => x.ToString()).ToArray()); ;
}
 
protected void btnTest3_Click(object sender, EventArgs e)
{
    txt.Text = string.Join(",", MultiSelectDropdown3.SelectedValue.Select(x => x.ToString()).ToArray()); ;
}
Supported Entity class
?
1
2
3
4
5
6
7
8
9
10
11
public class Customer
{
    public string CustomerID { get; set; }
    public string CustomerName { get; set; }
}
public class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
    public string Description { get; set; }
}
The output of the screen output would be:








Comments

Popular posts from this blog

GRIDVIEW GROUPING

When displaying data, we sometimes would like to group data for better user experience or when displaying long list of hierarchal data, we would want to display them in a tree view kind of structure. There is more than way of doing this, but I am going to explain achieving this functionality using  AJAX Collapsible Panel Extender Control . Overview: I am going to use  Adventure Works  as datasource. Every product in  Production.Product  table belongs to a product sub category. We fetch handful of products and the sub categories they belong to from the database. Our objective is to list all the available sub categories and allow user to  expand/collapse  to look/hide the list of products belonging to each subcategory. Database Connection Added following entry under  connectionStrings  element in  web.config . < add   name = "Sql"   connectionString="Data Source=(local); Initial  Catalog = AdventureWorks ...

Dynamic Generation of Word Document Report in ASP.NET with HTML

Overview Ever needed to generate Word documents from your ASP.NET applications? There are a couple of components which will help to generate Word documents, but using these components may have some overhead such as Component Registration, setting permissions, licenses, etc., Sometimes, it may even become difficult to understand their features and use them. Generating word document in ASP.NET with HTML is incredibly easy. The following sample demonstrates how to place Heading and Table dynamically in the word document in ASP.NET web applications using HTML. Requirements Microsoft Visual Web Developer 2005 Express Edition Create the Web Application project Add the new Web Site Application project (with name as Generate Word Document) and place the button (with name as btnGenerateDocument) in the Default.aspx web form as shown below. Double click the highlighted code behind file from the Solution Explorer and add the following namespaces. Listing 1 using  System...

GRIDVIEW ZOOM IMAGE

When you have images in your  GridView , you would most likely show them as thumbnails so as to not distort the whole layout. However user would want to look at the full image by clicking on the image or just hovering his mouse over it. In today’s applications, this is a basic requirement and there are just so many third party controls or plugins which would support this functionality. I am going do this conventional way using  javascript  way in this article.  On top of it, I am also going to explain how to get images from database using  HttpHandlers . Example: I am using  Adventure Works  as datasource. We fetch handful of products and bind them to the grid. When page is initially loaded, we retrieve products from Production . Product  table and bind them to the grid. We display some product attributes such as Product ID, Product Number, Product Name, List Price and product’s thumbnail. When user hover his mouse on the page, we fetch the f...