Wednesday, 18 September 2013

How to get CheckBoxList selected items in comma separated format in ASP.NET( C#/VB.NET) or How to set multiple selected values in ASP.NET checkboxlist

Hi friends, in this article I will explain about How to get CheckBoxList selected items in comma separated format in ASP.NET( C#/VB.NET) or How to set multiple selected values in ASP.NET checkboxlist.
I already explained in the previous articles about jQuery:How to check all checkboxes except one checkbox || jQuery :not() Selector ExampleMVC 4 Razor: How to Select / Deselect All Checkboxes inside a Webgrid in ASP.NET Application using C#.NET and How to Maintain selected Checkboxes state while paging in GridView?

In ASP.NET page add the following lines.
Interests:<asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatDirection ="Horizontal" >
            <asp:ListItem Value="Chess">Chess</asp:ListItem>
            <asp:ListItem Value="Carooms">Carooms</asp:ListItem>
            <asp:ListItem Value="Cricket">Cricket</asp:ListItem>

In C#:
  string interest = "";
        for (int i = 0; i < CheckBoxList1.Items.Count; i++)
        {
            if (CheckBoxList1.Items[i].Selected)
            {
                if (i == 0)
                {
                    interest += CheckBoxList1.Items[i].Value;
                }
                else
                {
                    interest += "," + CheckBoxList1.Items[i].Value;
                }
            }
        }



Validations:
<script type ="text/javascript"  language ="javascript" >
    function validate(){
        var uname = document.getElementById("TextBox1").value;
        if( uname == "")
        {
            alert("Enter Username");
            return false;
    }
    var role = document.getElementById("DropDownList1").selectedIndex;
    if (role == 0) {
        alert("Enter role");
        return false;
    }
    var listItems = document.getElementById("CheckBoxList1").getElementsByTagName("input");
    var itemcount = listItems.length;
    var iCount = 0;
    var isItemSelected = false;
    for (iCount = 0; iCount < itemcount; iCount++) {
        if (listItems[iCount].checked) {
            isItemSelected = true;
            break;
        }
    }
    if (!isItemSelected) {
        alert("Please select an Item.");
    }
    else {
        return true;
    }
    return false;
}
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode > 31
            && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

</script>

No comments:

Post a Comment

© 2012-2014 Aspdotnet-Kishore.blogspot.com. All Rights Reserved.
The content is copyrighted to Kishore and may not be reproduced on other websites without permission from the owner.