Decrease Font Size
Increase Font Size
   BLOG

ASP.NET - Get selected checkbox value in DataList

by bryian 3. June 2011 12:17

ASP.NET - Get selected checkbox value in DataList from code behind and jQuery|

ASP.NET - How to collect checkbox values in DataList |

ASP.NET - Getting CheckBox Value out of DataList

 

A while ago, someone at the forum has asked "how to retrieve the checkbox value from the ASP.NET DataList control". I took the opportunity to put together a sample code to achieve the requirement through the Code Behind and jQuery.
In this example, I'm using HTML Input (CheckBox) control in the DataList. Shown in listing 1 is the code use to get the selected checkbox value. The code will loop through the DataListItemCollection, find the CheckBox control by ID then do something if it was checked.

Listing 1:

void GetCheckedBox()
    {
        foreach (DataListItem li in BooksDataList.Items)
        {
            HtmlInputCheckBox cb = li.FindControl("FavChkBox") as HtmlInputCheckBox;

            if (cb != null)
            {
                if (cb.Checked)
                {
                    if (LblText.Text.Length > 0)
                        LblText.Text += ", ";

                    LblText.Text += cb.Value;
                }
            }
        }
    }

Let's say we decide not to write code to loop through the DataListItemCollection, we can collect the selected CheckBox value through the client-side script. Shown in Listing 2 is the jQuery script use to collect the selected CheckBox value. When the user hit the submit button, the script will retrieve all the CheckBox value in the DataList control, stored in an array and later save it to a hidden field.

Listing 2:

<script type="text/javascript">
        $(document).ready(function () {
            //check all
             $("[id$='chkAll']").click(
             function () {
                 $("INPUT[type='checkbox']").attr('checked', $("[id$='chkAll']").is(':checked'));
             });

            $("[id$='btnSubmit']").click(function () {
                var ISBN = [];

                $("[id$='BooksDataList'] input[type=checkbox]:checked").each(function () {
                    ISBN.push($(this).val());
                });

                $("[id$='HiddenField1']").val(ISBN);
            });
        });
    </script>

In the code behind we can retrieve the hidden field value like this "HiddenField1.Value;"

Conclusion

I hope someone will find this information useful and make your programming job easier. If you find any bugs or disagree with the contents or want to help improve this article, please drop me a line and I'll work with you to correct it. I would suggest downloading the demo and explore it in order to grasp the full concept of it because I might miss some important information in this article. Please send me an email if you want to help improve this article.

Watch this script in action

Demo

Downloads

Download

Comments are closed