关于ASP.NET中的CheckBoxList问题

POWER_WONG 2010-09-08 11:00:16
各位好!
现在一个问题要请教下:
我在做一个ASP.NET的项目时用到了CheckBoxList,它里面的数据项是用后台数据库获得到,用ObjectDataSource作为其数据源,现在把它放在页面中,运行时显示没有问题,我现在想编程让它的几个项处于选择状态,但怎么也实现不了,如果不用数据源方式来绑定它的项的话就可以实现相关的选择状态,不知何故,望名位兄弟帮下忙,谢谢了!

我试了用如下代码都不能实现选择状态:
foreach (ListItem li in CheckBoxList1.Items)
{
li.Selected = true;
}

或者假设CheckBoxList中有一个绑定项的文本为Test,用如下代码也不能使相应的项选定:
string value1 = "Test";
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
ListItem li = CheckBoxList1.Items.FindByText(value1);
if (li != null)
{
li.Selected = true;
}
}
是不是因为CheckBoxList绑定的是数据库的资料的原因?
...全文
200 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zming 2010-09-09
  • 打赏
  • 举报
回复
为 CheckBoxList 添加 OnDataBound 事件,在 OnDataBound 事件处理程序中,遍历 CheckBoxList.Items

示例:


protected void CheckBoxList_DataBound(object sender, EventArgs e)
{
CheckBoxList chkList = sender as CheckBoxList;
foreach (ListItem item in chkList.Items)
{
if (......)
{
item.Selected = true;
}
}
}
POWER_WONG 2010-09-09
  • 打赏
  • 举报
回复
问题已解决,谢谢各位了!
wuyq11和zming的方法都可以,再次谢谢!
kensouterry 2010-09-09
  • 打赏
  • 举报
回复

protected void Page_Load(object sender, EventArgs e)
{

CheckBoxList1.Items[0].Selected = true;
CheckBoxList1.Items[1].Selected = true;
}

cs codes

但是你表现层是怎么绑定数据的,你确定绑定数据的时候是绑定到ListItem里面的,
<asp:ListItem>1</asp:ListItem>
或者说你根本没有ListItem?


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:CheckBoxList ID="CheckBoxList1" runat="server" Width="169px">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
</asp:CheckBoxList>

</div>
</form>
</body>
</html>
wuyq11 2010-09-08
  • 打赏
  • 举报
回复
protected void CheckBoxList1_PreRender(object sender, EventArgs e)
{
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
CheckBoxList1.Items[i].Selected = true;
}
}
q107770540 2010-09-08
  • 打赏
  • 举报
回复
if (!IsPostBack)
{
Bind();//绑定checkboxlist
foreach (ListItem li in CheckBoxList1.Items)
{
li.Selected = true;
}
}



string value1 = "8";
foreach (ListItem li in CheckBoxList1.Items)
{
if (li.Text == value1)
{
li.Selected = true;
}
}

111,129

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧