Prateek Singla
Prateek Singla

Reputation: 75

to disable a label of repeater on some condition in asp .net

Markup

<HeaderTemplate>
    <table>
        <tr>
            <th>
                <asp:Label ID="label12" runat="server" Text="Editor"></asp:Label>
            </th>
        </tr>
</HeaderTemplate>

Code behind

protected void ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Label label12 = (Label)e.Item.FindControl("label12");
        Label activeLabel = (Label)e.Item.FindControl("lblEditor");
        string s = activeLabel.Text;
        if (s != "Sao Palo")
        {
            activeLabel.Visible = true;
            label12.Visible = true;
        }
        else
        {                    
            activeLabel.Visible = false;
            label12.Visible = false;   
        }
    }
}

I am getting a NullReferenceException at:

label12.visible=true;

Upvotes: 2

Views: 1691

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460058

This label is in the header, that's why it cannot be found in the repeater-items. So change e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) to e.Item.ItemType == ListItemType.Header.

protected void ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Header)
    {
        Label label12 = (Label)e.Item.FindControl("label12");
        // ...
    }
}

But since the other label is not in the hader but in in an item you need a different approach. You can also get the header-label via Repeater.Controls[0].Controls[0].FindControl("label12");.

So this should work:

protected void ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Label label12 = (Label)((Repeater)sender).Controls[0].Controls[0].FindControl("label12");;
        Label activeLabel = (Label)e.Item.FindControl("lblEditor");
        string s = activeLabel.Text;
        if (s != "Sao Palo")
        {
            activeLabel.Visible = true;
            label12.Visible = true;
        }
        else
        {                    
            activeLabel.Visible = false;
            label12.Visible = false;   
        }
    }
}

Upvotes: 2

Related Questions