Sunday 16 September 2012

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.
[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
$(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
.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.
public class HiddenData
{
    public string DataSource { get; set; }
    public IEnumerable<string> SelectedValue { get; set; }
}
Now let us test this control in the Test project.
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <cc1:MultiSelectDropdown ID="MultiSelectDropdown1" runat="server" Width="150px" Height="20px" /><br /><br />
    <cc1:MultiSelectDropdown ID="MultiSelectDropdown2" runat="server" Width="200px" Height="20px" /><br /><br />
    <cc1:MultiSelectDropdown ID="MultiSelectDropdown3" runat="server" Width="100px" Height="20px" /><br /><br />

    <asp:Button ID="btnTest1" Text="Get Values of MultiSelectDropdown1" runat="server" onclick="btnTest1_Click" /><br /><br />
    <asp:Button ID="btnTest2" Text="Get Values of MultiSelectDropdown2" runat="server" onclick="btnTest2_Click" /><br /><br />
    <asp:Button ID="btnTest3" Text="Get Values of MultiSelectDropdown3" runat="server" onclick="btnTest3_Click" /><br /><br />
    <asp:TextBox ID="txt" Text="" runat="server" Width="700px"></asp:TextBox>
    <br /><br /><br /><br />
    <asp:DropDownList ID="ddlList" runat="server" Width="200px"></asp:DropDownList><br /><br />
</asp:Content>
The Codebehind code
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
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:






download the working example of the source code in C# here.

2 Responses to “Multi-Selection Dropdown box in ASP.NET”

  • bhupendra tiwari says:
    30 January 2013 at 14:17

    please provide download link

  • Thirumalai M says:
    30 January 2013 at 16:39

    Hi, The source code link is updated. Pls verify that. I have given only C#, so pls convert the same to VB if required.

Post a Comment