markzzz
markzzz

Reputation: 48065

How can I assign an ID to a checkbox in a Repeater?

I have these checkbox on a Repeater:

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

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

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

every checkbox must coincide with a Page ID taken from Database (every repeaterCategories Item has its unique id, so that one).

How can I set it? So, at the postback, I check which CheckBox Controls are Checked and I get the IDs.

Upvotes: 1

Views: 1608

Answers (2)

mtsiakiris
mtsiakiris

Reputation: 190

User control page:

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

Code behind:

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)
    {

    }
}

At your repeater page:

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

Inside the repeater:

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

        <uc1:WebUserControl runat="server" ID="WebUserControl" MyProperty="My_ID_Value" />

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

You can add as many properties you like on your web user control.

Upvotes: 0

Erhan Korkut
Erhan Korkut

Reputation: 36

can you try add custom attribute like this

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

Upvotes: 2

Related Questions