How to FindControls in repeater control?

10,713

Solution 1

You can toggle the enabled property of the button control using declarative syntax and display and format the Event_Start_Date using the Eval methods format parameter. This way there is no need for the CheckEnability method.

<asp:Repeater>
    <table>
         <tr>
            <td align="right" style=" font-weight:bold">Start Date : </td>
            <td><%# Eval("Event_Start_Date", "{0:yyyy-MM-dd}")%></td>
        </tr>
         <asp:Button ID="ParticipateBtn" Enabled='<%# Convert.ToDateTime(Eval("Event_Start_Date") ) < DateTime.Now %>' CommandName="Participate" CommandArgument='<%# Eval("Event_Id") + "|" + Eval("Event_Name") + "|" + Eval("Volume") + "|" + Eval("Tournament_Id") %>' runat="server" Text="Participate" />&nbsp;&nbsp;
    </ItemTemplate>
    <FooterTemplate></FooterTemplate>
    <SeparatorTemplate><hr style="color:Silver; height:1px;" /></SeparatorTemplate>
</asp:Repeater>

Solution 2

Controls don't exist in the repeater until it has been databound, and then each control in the ItemTemplate exists once per item - so if you bind to a source with 3 items, there will be 3 ParticipateBtns. You need to know which one you want before you can find it. Once you do, you can get it like so:

myRepeater.Items[1].FindControl("ParticipateBtn");

Solution 3

Add the attribute OnItemDataBound="repeater_ItemDataBound" to your repeater.

Then in your code behind do:

void repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e) 
{
    if (((DateTime)e.Item.DataItem).Date < DateTime.Now.Date)
    {
        Button participate = (Button)e.Item.FindControl("ParticipateBtn");
        participate.Enabled = false;              
    }      
}
Share:
10,713
Jignesh
Author by

Jignesh

Updated on June 05, 2022

Comments

  • Jignesh
    Jignesh almost 2 years

    I want to enable or disable 'ParticipateBtn' depending on EventStartDate. I am getting this error:Object reference not set to an instance of an object.

    Start Date : <%# CheckEnability((DateTime)Eval("Event_Start_Date")) %>

            <asp:Button runat="server" 
                ID="ParticipateBtn" 
                CommandName="Participate" 
                CommandArgument='<%# Eval("Event_Id") + "|" + Eval("Event_Name") + "|" + Eval("Volume") + "|" + Eval("Tournament_Id") %>' 
                Text="Participate" />&nbsp;&nbsp;
    
        </ItemTemplate>
    
        <FooterTemplate></FooterTemplate>
    
        <SeparatorTemplate>
            <hr style="color:Silver; height:1px;" />
        </SeparatorTemplate>
    
    </asp:Repeater>
    

    The code behind...

    //Code behind
    protected  string CheckEnability(DateTime eventstartdate)
    {
    
        if (eventstartdate.Date < DateTime.Now.Date)
        {
            Button btn = (Button)Repeater1.FindControl("ParticipateBtn");
            btn.Enabled = false;              
        }           
        return eventstartdate.ToString("yyyy-MM-dd");
    }