【问题标题】:How can I assign an ID to a checkbox in a Repeater?如何将 ID 分配给中继器中的复选框?
【发布时间】:2013-04-16 18:15:36
【问题描述】:

我在中继器上有这些复选框:

<asp:Repeater id="repeaterCategories" runat="server">
    <ItemTemplate>
        ...

        <asp:CheckBox ID="chbCategoria" Text="My Label" runat="server" />

        ...
    </ItemTemplate>
</asp:Repeater>

每个复选框都必须与从数据库中获取的页面 ID 一致(每个 repeaterCategories 项都有其唯一的 ID,因此只有一个)。

如何设置?因此,在回发时,我检查了哪些 CheckBox 控件被选中并获得了 ID。

【问题讨论】:

    标签: c# checkbox user-controls webforms repeater


    【解决方案1】:

    你可以尝试添加这样的自定义属性

    protected void repeaterCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            CheckBox chk = e.Item.FindControl("chbCategoria") as CheckBox ;
            chk.Attributes.Add("PageID", DataBinder.Eval(e.Item.DataItem, "DB_FIELD").ToString());
        }
    }
    

    【讨论】:

    • 看起来不错!为什么if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    • 用于在 ItemTemplate 或 AlternatingItemTemplate 中查找控件
    • 好吧,但我只有ItemTemplate,所以它只会重复那个:)
    【解决方案2】:

    用户控制页面:

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
    <asp:CheckBox id ="MyCheckBox" runat="server"/>
    

    后面的代码:

    using System;
    
    public partial class WebUserControl : System.Web.UI.UserControl
    {
        private string _myProperty;
        public string MyProperty 
        {
            get { return this._myProperty; }
            set { this._myProperty = value; }
        }
    
        public bool IsChecked
        {
            get 
            {
                return this.MyCheckBox.Checked;
            }
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    }
    

    在您的转发器页面:

    <%@ Register Src="~/WebUserControl.ascx" TagPrefix="uc1" TagName="WebUserControl" %>
    

    中继器内部:

    <asp:Repeater id="repeaterCategories" runat="server">
        <ItemTemplate>
            ...
    
            <uc1:WebUserControl runat="server" ID="WebUserControl" MyProperty="My_ID_Value" />
    
            ...
        </ItemTemplate>
    </asp:Repeater>
    

    您可以在 Web 用户控件上添加任意数量的属性。

    【讨论】:

    • 嗯,不是真的!尝试使用checkBox.Attributes.Add("category-id", ((ArchiePagina)e.Item.DataItem).UniqueID);,但它将属性添加到跨度,而不是复选框:O
    • 我不明白你在说什么:O
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多