ASP.Net C# code to add CheckBoxList onclick event programmatically

Updated on 03 Jul 2012,
Published on 21 Oct 2009

The ASP.Net CheckBoxList onclick event can also be added using C# code dynamically if there are number of list items. You can add the onclick event as an inline attribute simply if there are one, two or three list items that will render as checkbox controls as we discussed in the previous tutorial: Adding CheckBoxList onclick client side javascript in ASP.Net. But if there are number of list items that need same client side click event then you can use this second way to attach the event using C# code programmatically. Here we will use the Add method of Attributes collection property of the ListItem collection of CheckBoxList. The Add method of Attributes collection property accepts two string type parameters:

1. key: it accepts the name of the attribute that you want to add.

2. value: it accepts the value for the specified attribute.

You can use the following C# code to add the CheckboxList item's onlcick event dynamically:

CheckBoxList1.Items[0].Attributes.Add("onclick", "alert('This is a JavaScript alert message box.')");

Above C# code is the simplest way to add the attribute to the associated list item of the checkboxlist control programmatically. In the above code we have specified the index number 0 for the Items collection property of checkboxlist that will add the specified attribute to the first checkbox type list item. But for the previous tutorial: ASP.Net CheckBoxList Validation using JavaScript we need the C# code to add the onclick event to multiple checkbox list items of the control. For that purpose you can use the following C# code to attach the same client side onlcick event to each ListItem placed inside the ASP.Net CheckBoxList control:

foreach (ListItem listitem in CheckBoxList1.Items)
    listitem.Attributes.Add("onclick", "chkCount(this)");

In the above sample code we have used C# foreach loop over the List Items Collection of CheckBoxList control. Inside the loop, we have used the listitem object for each list item reference provided by the foreach loop over the collection of items.


Get the output for above discussed code from the following link:

CheckBoxList Control JavaScript Validation

Continue to the next tutorial: ASP.Net CheckBoxList Select All using C# to learn how to check all the checkbox type list items with a single click using server side event handler of checkbox control.

1 Responses to "ASP.Net C# code to add CheckBoxList onclick event programmatically"
Well what if I want to programatically add a callback to a C# function on a listitem? Not to a javascript function?
Leave a Comment
* required
* required
* will not be published
* optional
* hint:
  • Subscribe via Email