首页 > 解决方案 > Asp.Net:使用 ListView 控件创建自定义 CheckBoxList

问题描述

使用 VS 2019、c# 4.8 和 Asp.net Webforms,我想使用 ListView 控件创建一个 CheckBoxList。

我希望它看起来像这样: 在此处输入图像描述

首先,我为数据绑定创建了一个类:

public class Category
{
    public Guid CatId { get; set; }
    public string CategoryName { get; set; }
    public bool IsChecked { get; set; }
}

这是html:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div class="divStyle">
            <asp:ListView ID="CategoryCheckList" runat="server" class="CListStyle"
                GroupItemCount="3" ItemPlaceholderID="itemsGoHere"
                GroupPlaceholderID="groupsGoHere">
                <LayoutTemplate>
                    <table>
                        <asp:PlaceHolder runat="server" ID="groupsGoHere"></asp:PlaceHolder>
                    </table>
                </LayoutTemplate>
                <GroupTemplate>
                    <tr>
                        <asp:PlaceHolder runat="server" ID="itemsGoHere"></asp:PlaceHolder>
                    </tr>
                </GroupTemplate>
                <ItemTemplate>
                    <%--<td class="CListStyle"><%#Eval("CategoryName")%></td>--%>
                    <td><asp:CheckBox id="itemCheckBox" runat="server" /></td>
                    <asp:Label  ID="itemCheckBoxLabel" runat="server" Text='<%# Eval("CategoryName")%>'></asp:Label>   
                </ItemTemplate>
            </asp:ListView>           
        </div>        
    </form>
</body>
</html>

这是代码隐藏:

public partial class WebForm1 : System.Web.UI.Page
{
    private List<Category> _categories;

    protected void Page_Load(object sender, EventArgs e)
    {
        LoadCategories();
    }

    void LoadCategories()
    {
        List<Category> list = new List<Category>();
        list.Add(new Category { CatId = new Guid(), CategoryName = "xxxx" });
        list.Add(new Category { CatId = new Guid(), CategoryName = "xxxx" });
        list.Add(new Category { CatId = new Guid(), CategoryName = "xxxx" });
        list.Add(new Category { CatId = new Guid(), CategoryName = "xxxx" });
        list.Add(new Category { CatId = new Guid(), CategoryName = "xxxx" });
        list.Add(new Category { CatId = new Guid(), CategoryName = "xxxx" });
        list.Add(new Category { CatId = new Guid(), CategoryName = "xxxx" });
        list.Add(new Category { CatId = new Guid(), CategoryName = "xxxx" });
        _categories = list;
        CategoryCheckList.DataSource = _categories;
        CategoryCheckList.DataBind();
    }

    public List<Category> Categories { get => _categories; set => _categories = value; }
}

当我运行它时,它是这样的:

在此处输入图像描述

  1. 我需要做什么才能使它看起来正确,标签在复选框旁边的位置?

  2. 我将 CatId 绑定到什么?当我们进行回发时,我们需要遍历列表并获取检查项目的 Guid Id。

谢谢你。

标签: c#asp.netlistview

解决方案


推荐阅读