Friday, 25 January 2013

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:








No comments:

Post a Comment

Note: only a member of this blog may post a comment.