views:

190

answers:

3

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.

    <table>
         <tr>
            <td align="right" style=" font-weight:bold">Start Date : </td>
            <td><%# CheckEnability((DateTime)Eval("Event_Start_Date")) %></td>
        </tr>


         <asp:Button ID="ParticipateBtn" 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>

//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");
}
+2  A: 

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");
Rex M
+1  A: 

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>
Phaedrus
A: 

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.FindControl("ParticipateBtn");
        participate.Enabled = false;              
    }      
}

`

Aequitarum Custos