ASP.NET CheckBoxList 数据绑定问题

发布于 2024-07-20 04:59:17 字数 803 浏览 9 评论 0原文

是否可以对 ASP.NET CheckBoxList 进行数据绑定,以便数据中的字符串值成为复选框的标签,而布尔值则选中/取消选中该框?

在我的 asp.net webform 上,我有一个像这样的 CheckBoxList:

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

在后面的代码中,我有这样的代码:

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 =“Checked”。 结果是一样的。 我似乎无法找到一种方法进行数据绑定并自动选中/取消选中复选框。

目前,我通过为 DataBound 事件中的适当项目设置 selected = true 来解决该问题。 似乎有一个更清洁的解决方案超出了我的掌握。

谢谢

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?

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

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

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();

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.

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.

Thank You

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

甜柠檬 2024-07-27 04:59:17

编辑:无法通过标记来做到这一点。 DataValueField 无法确定复选框项是否被选中。 它检索或存储要在回发中使用的值。 DataValueField 是常见的CheckBoxLists、RadioButtonLists、ListControl 等。

正如您已经发现的那样,这是预先选择复选框的唯一方法。

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

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

EDIT: 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.

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;
情绪 2024-07-27 04:59:17

在厌倦了 OnItemDataBound 绑定后,我为此创建了一个自定义控件。
它可以让您绑定 Selected 属性。 通过更改自定义控件的派生来源,您可以轻松地为 RadioButtonList 创建相同的控件。

要使用此功能,只需在标记中创建控件时添加 DataCheckedField 属性即可。 请记住在您的 web.config 文件中引用自定义控件。

标记

<myControls:SimpleCheckBoxList runat="server" ID="chkListRoles"
                               DataCheckedField="InRole"
                               DataTextField="UserName"
                               DataValueField="UserId" />

控件代码

public class SimpleCheckBoxList : System.Web.UI.WebControls.CheckBoxList
{
    public string DataCheckedField
    {
        get
        {
            string s = (string)ViewState["DataCheckedField"];
            return (s == null) ? String.Empty : s;
        }
        set
        {
            ViewState["DataCheckedField"] = value;
            if (Initialized)
                OnDataPropertyChanged();
        }
    }

    protected override void PerformDataBinding(IEnumerable dataSource)
    {
        if (dataSource != null)
        {
            if (!this.AppendDataBoundItems)
                this.Items.Clear();

            if (dataSource is ICollection)
                this.Items.Capacity = (dataSource as ICollection).Count + this.Items.Count;

            foreach (object dataItem in dataSource)
            {
                ListItem item = new ListItem()
                {
                    Text = DataBinder.GetPropertyValue(dataItem, DataTextField).ToString(),
                    Value = DataBinder.GetPropertyValue(dataItem, DataValueField).ToString(),
                    Selected = (DataCheckedField.Length > 0) ? (bool)DataBinder.GetPropertyValue(dataItem, DataCheckedField) : false
                };
                this.Items.Add(item);
            }
        }
    }
}

I made a custom control for this, after getting tired of the OnItemDataBound-binding.
It will let you bind the Selected attribute. You can easily make the same control for RadioButtonList by changing what the custom control derives from.

To use this, simply add the DataCheckedField attribute when you create the control in your markup. Remember to reference the custom controls in your web.config file.

Markup

<myControls:SimpleCheckBoxList runat="server" ID="chkListRoles"
                               DataCheckedField="InRole"
                               DataTextField="UserName"
                               DataValueField="UserId" />

Code for the control

public class SimpleCheckBoxList : System.Web.UI.WebControls.CheckBoxList
{
    public string DataCheckedField
    {
        get
        {
            string s = (string)ViewState["DataCheckedField"];
            return (s == null) ? String.Empty : s;
        }
        set
        {
            ViewState["DataCheckedField"] = value;
            if (Initialized)
                OnDataPropertyChanged();
        }
    }

    protected override void PerformDataBinding(IEnumerable dataSource)
    {
        if (dataSource != null)
        {
            if (!this.AppendDataBoundItems)
                this.Items.Clear();

            if (dataSource is ICollection)
                this.Items.Capacity = (dataSource as ICollection).Count + this.Items.Count;

            foreach (object dataItem in dataSource)
            {
                ListItem item = new ListItem()
                {
                    Text = DataBinder.GetPropertyValue(dataItem, DataTextField).ToString(),
                    Value = DataBinder.GetPropertyValue(dataItem, DataValueField).ToString(),
                    Selected = (DataCheckedField.Length > 0) ? (bool)DataBinder.GetPropertyValue(dataItem, DataCheckedField) : false
                };
                this.Items.Add(item);
            }
        }
    }
}
那小子欠揍 2024-07-27 04:59:17

使用标记是不可能的。 您可以做的是像您希望的那样绑定复选框列表 - 使用 DataValueField 中的布尔值,然后只需将其添加为 OnDataBound 事件。

protected void myCheckBoxList_DataBound(object sender, EventArgs e)
    {
        foreach (ListItem item in myCheckBoxList.Items)
        {
            item.Selected = bool.Parse(item.Value);
        }
    }

该解决方案与 Jose Basilio 提出的解决方案之间的区别在于,该解决方案适用于所有类型的数据绑定方法。 例如,使用 v4.5 中的新 ModelBinding 功能与 SelectMethod 进行绑定。

It's not possible using markup. What you can do is to bind the checkboxlist like you wanted it to work - with the bool in the DataValueField, and then simply add this as OnDataBound event.

protected void myCheckBoxList_DataBound(object sender, EventArgs e)
    {
        foreach (ListItem item in myCheckBoxList.Items)
        {
            item.Selected = bool.Parse(item.Value);
        }
    }

The difference between this solution and the one proposed by Jose Basilio is that this one works with all kind of databinding methods. For example binding with a SelectMethod using the new ModelBinding feature in v4.5.

灯下孤影 2024-07-27 04:59:17

使用 DataList 可能是另一种选择

<asp:DataList ID="dataListRoles" runat="server">
    <ItemTemplate>
        <asp:CheckBox runat="server" Text='<%# Eval("UserName ") %>' Checked='<%# Eval("IsInRole") %>' />
    </ItemTemplate>
</asp:DataList>

Using a DataList could be another option

<asp:DataList ID="dataListRoles" runat="server">
    <ItemTemplate>
        <asp:CheckBox runat="server" Text='<%# Eval("UserName ") %>' Checked='<%# Eval("IsInRole") %>' />
    </ItemTemplate>
</asp:DataList>
梦毁影碎の 2024-07-27 04:59:17

我认为你必须告诉控件将其绑定到什么属性......在本例中为“InRole”。

我玩了一下,似乎没有办法绑定到复选框的选择,你必须自己做。 我能够绑定到清单的文本和值,它们似乎只处理列表中每个复选框的标签。

I would think you would have to tell the control what property to bind it to...in this case "InRole".

I played around with it and seems like there is noway to bind to the selection of the checkbox, you have to do it yourself. I was able to bind to the text and values of the checklist which only seem to deal with the label of each checkbox in the list.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文