ASP.NET C# 禁用/启用 ListItems






4.75/5 (12投票s)
2004年8月27日
1分钟阅读

175884
本文演示了如何在 ASP.NET CheckBoxList 服务器控件中禁用/启用单个 ListItems。
简要介绍
你是否曾经希望在 ASP.NET 中的 ListControl
服务器控件中禁用/启用单个列表项?你可能尝试过将属性添加到 CheckBoxList
或 DropDownList
等服务器控件中的单个 ListItem
中?这是不可能的,并且是一个已知错误。我需要实现一种方法,当某个项被选中/取消选中时,禁用/启用 CheckBoxList
的单个项。该问题通过添加一个由 CheckBoxList
的 onclick
事件调用的 JavaScript 函数来解决。
说明
- 将一个
CheckBoxList
添加到你的 ASP.NET WebForm 中,并为其赋予一个ID
为checkBoxListTest
。 - 在
Page_Load
事件中添加对LoadCheckBoxList
的调用。 - 将
LoadCheckBoxList
方法添加到你的网页类中。 - 将 JavaScript 函数添加到 HTML 的 head 部分内。
ASP.NET 代码隐藏文件
以下方法将 onclick
函数 disableListItems
添加到 CheckBoxList
属性集合中。当它被选中时,该函数将禁用列表中的所有项,除了最后一个项。该方法还向 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')");
// Add three items to the CheckBoxList.
for(int i=0; i < 3; i++)
{
ListItem item = new ListItem(i.ToString(), i.ToString());
this.checkBoxListTest.Items.Add(item);
}
}
以下代码是 CheckBoxList
的 onclick
事件调用的 JavaScript 函数。
JavaScript 函数
/*******************************************************************
This is the javascript function that is invoked when the checkboxlist
is clicked.
Function: disableListItems.
Inputs: checkBoxListId - The id of the checkbox list.
checkBoxIndex - The index of the checkbox to verify.
i.e If the 4th checkbox is clicked and
you want the other checkboxes to be
disabled the index would be 3.
numOfItems - The number of checkboxes in the list.
Purpose: Disables all the checkboxes when the checkbox to verify is
checked. The checkbox to verify is never disabled.
********************************************************************/
function disableListItems(checkBoxListId, checkBoxIndex, numOfItems)
{
// Get the checkboxlist object.
objCtrl = document.getElementById(checkBoxListId);
// Does the checkboxlist not exist?
if(objCtrl == null)
{
return;
}
var i = 0;
var objItem = null;
// Get the checkbox to verify.
var objItemChecked =
document.getElementById(checkBoxListId + '_' + checkBoxIndex);
// Does the individual checkbox exist?
if(objItemChecked == null)
{
return;
}
// Is the checkbox to verify checked?
var isChecked = objItemChecked.checked;
// Loop through the checkboxes in the list.
for(i = 0; i < numOfItems; i++)
{
objItem = document.getElementById(checkBoxListId + '_' + i);
if(objItem == null)
{
continue;
}
// If i does not equal the checkbox that is never to be disabled.
if(i != checkBoxIndex)
{
// Disable/Enable the checkbox.
objItem.disabled = isChecked;
// Should the checkbox be disabled?
if(isChecked)
{
// Uncheck the checkbox.
objItem.checked = false;
}
}
}
}
结论
以上代码表明,在 ASP.NET 中,可以在 ListBox
服务器控件内启用/禁用单个项。你可以修改 C# 和 JavaScript 代码以满足你的需求。