Search code examples
c#asp.netcontrolsrepeater

How to FindControls in repeater control?


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

Solution

  • 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>