A Brief Introduction
Have you ever wanted to disable/enable individual list items in a ListControl
Server Control in ASP.NET? You might have tried to add attributes to the individual ListItem
s in a Server Control such as a CheckBoxList
or DropDownList
? It's impossible and a known bug. I needed to implement a way to disable/enable individual items of a CheckBoxList
when a certain item was checked/unchecked. The problem was solved by adding a JavaScript function that is invoked by the onclick
event of the CheckBoxList
.
Instructions
- Add a
CheckBoxList
to your ASP.NET WebForm and give it an ID
of checkBoxListTest
.
- Add a call to the
LoadCheckBoxList
in the Page_Load
event.
- Add the
LoadCheckBoxList
method to your webpage class.
- Add the JavaScript function inside the head of the HTML.
ASP.NET CodeBehind
The following method adds the onclick
function disableListItems
to the CheckBoxList
attributes collection. The function will disable all the items except for the last item in the list when it is checked. The method also adds three items to the CheckBoxList
.
private void Page_Load(object sender, System.EventArgs e)
{
if(!this.IsPostBack)
{
LoadCheckBoxList();
}
}
private void LoadCheckBoxList()
{
this.checkBoxListTest.Attributes.Add("onclick",
"disableListItems('checkBoxListTest', '2', '3')");
for(int i=0; i < 3; i++)
{
ListItem item = new ListItem(i.ToString(), i.ToString());
this.checkBoxListTest.Items.Add(item);
}
}
The following code is the JavaScript function that is invoked by the onclick
event of the CheckBoxList
.
JavaScript Function
function disableListItems(checkBoxListId, checkBoxIndex, numOfItems)
{
objCtrl = document.getElementById(checkBoxListId);
if(objCtrl == null)
{
return;
}
var i = 0;
var objItem = null;
var objItemChecked =
document.getElementById(checkBoxListId + '_' + checkBoxIndex);
if(objItemChecked == null)
{
return;
}
var isChecked = objItemChecked.checked;
for(i = 0; i < numOfItems; i++)
{
objItem = document.getElementById(checkBoxListId + '_' + i);
if(objItem == null)
{
continue;
}
if(i != checkBoxIndex)
{
objItem.disabled = isChecked;
if(isChecked)
{
objItem.checked = false;
}
}
}
}
Conclusion
The above code shows that it is possible to enable/disable individual items within a ListBox
Server Control in ASP.NET. You can modify the C# and JavaScript code to meet your needs.