Monday, March 4, 2013

multi-select dropdownlist in ASP.NET

(this one is heavily followed the article in dotnetfunda; credits go to the developer)

While doing the coding, at times you will need your user to select few options.
Using check-box or radio button is a good option, but they consume quite a space.
Reporting service comes with the multi-select dropdown-list control,



but you could not find the similar one in standard ASP .NET controls.
While searching for the multi-select dropdown list in ASP .NET, I bumped into this article. It's almost similar to what you might expected.

By adding extra ASP checkbox (let's call it: ID="checkAll") on top of CheckBoxList:

   
       

and some javascript:

    

    // http://stackoverflow.com/questions/5821993/checkboxlist-items-using-javascript
    function CheckAll() {
        var intIndex = 0;
        var rowCount = document.getElementById('<%=cblItems.ClientID %>').getElementsByTagName("input").length;
        for (intIndex = 0; intIndex < rowCount; intIndex++) {
            if (document.getElementById('<%=checkAll.ClientID %>').checked == true) {
                if (document.getElementById('<%=cblItems.ClientID %>' + "_" + intIndex)) {
                    if (document.getElementById('<%=cblItems.ClientID %>' + "_" + intIndex).disabled != true)
                        document.getElementById('<%=cblItems.ClientID %>' + "_" + intIndex).checked = true;
                }
            }
            else {
                if (document.getElementById('<%=cblItems.ClientID %>' + "_" + intIndex)) {
                    if (document.getElementById('<%=cblItems.ClientID %>' + "_" + intIndex).disabled != true)
                        document.getElementById('<%=cblItems.ClientID %>' + "_" + intIndex).checked = false;
                }
            }
        }
    }

    function ClearAll() {
        var intIndex = 0;
        var flag = 0;
        var rowCount = document.getElementById('<%=cblItems.ClientID %>').getElementsByTagName("input").length;
        for (intIndex = 0; intIndex < rowCount; intIndex++) {
            if (document.getElementById('<%=cblItems.ClientID %>' + "_" + intIndex)) {
                if (document.getElementById('<%=cblItems.ClientID %>' + "_" + intIndex).checked == true) {
                    flag = 1;
                }
                else {
                    flag = 0;
                    break;
                }
            }
        }
        if (flag == 0)
            document.getElementById('<%=checkAll.ClientID %>').checked = false;
        else
            document.getElementById('<%=checkAll.ClientID %>').checked = true;

    }

A re-usable user-control is at your disposal:



You can get the full source-code.

And you have more options:
1) dropdown-check-list
2) jQuery UI MultiSelect Widget

1 comment:

taro said...

Source code had broken link.