ASP.NET的CheckBoxList数据绑定问题 [英] ASP.NET CheckBoxList DataBinding Question

查看:179
本文介绍了ASP.NET的CheckBoxList数据绑定问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在数据绑定ASP.NET的CheckBoxList使得在数据的字符串值变成复选框的标签和一个布尔值检查/取消选中复选框?

Is it possible to DataBind an ASP.NET CheckBoxList such that a string value in the data becomes the label of the check box and a bool value checks/unchecks the box?

在我的asp.net Web窗体我有这样一个的CheckBoxList:

On my asp.net webform I have a CheckBoxList like this:

<asp:CheckBoxList runat="server" ID="chkListRoles" DataTextField="UserName" DataValueField="InRole" />

在code后面我有这个code:

In the code behind I have this code:

var usersInRole = new List<UserInRole> 
{ 
  new UserInRole { UserName = "Frank", InRole = false},
  new UserInRole{UserName = "Linda", InRole = true},
  new UserInRole{UserName = "James", InRole = true},
};

chkListRoles.DataSource = usersInRole;
chkListRoles.DataBind();

我有点希望的复选框会被选中时InRole = TRUE。我也试着InRole =选中。结果是相同的。我似乎无法找到一种方法,数据绑定,并自动拥有的复选框选中/取消。

I was kinda hoping that the check boxes would be checked when InRole = true. I've also tried InRole = "Checked". The results were the same. I can't seem to find a way to DataBind and automagically have the check boxes checked/unchecked.

目前我通过设置选择= TRUE在DataBound事件适当的项目解决问题。好像有一个清洁的解决方案只是超出了我的把握。

Currently I solve the problem by setting selected = true for the appropriate items in the DataBound event. Seems like there's a cleaner solution just beyond my grasp.

感谢您

推荐答案

编辑:有没有办法通过标记来做到这一点。该DataValueField没有确定复选框项是否检查与否。它检索或存储在回传所使用的值。在<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.datavaluefield.aspx\">DataValueField通用于CheckBoxLists,RadioButtonLists,列表控件等。

There's no way to do this through the Markup. The DataValueField does not determine whether the checkbox item is check or not. It retrieves or stores the value to be used in postbacks. The DataValueField is common across CheckBoxLists, RadioButtonLists, ListControl, etc.

这是即将pre-选择复选框因为你已经发现的唯一出路。

This is about the only way to pre-select the checkboxes as you already found out.

chkListRoles.DataSource = usersInRole;
chkListRoles.DataBind();

foreach(ListItem item in chkListRoles.Items)
 item.Selected = usersInRole.Find(u => u.UserName == item.Text).InRole;

这篇关于ASP.NET的CheckBoxList数据绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆