Access first , 2nd, 3rd ......nth item in Repeater control

If you are an ASP.Net Developer, you must have used Repeater control to bind data from any data source. The data source could be XML, SQL etc.
Rather than describing how to bind data with Repeater Control, in this blog, I will describe how to access nth item to apply CSS.

I got a task where I have to bind data in such a way that each row should contain 5 items. As of now, it looks like a normal binding and I feel no issue with this line. But there was a twist in this binding.
The condition was to apply a special CSS class on 5th item in each row.

This can be achieved by ItemDataBound method of Repeater Control.


ASPX Code

A Repeater control with ItemTemplate and a value to be bind using Eval

<asp:Repeater ID="rptHead" runat="server" OnItemDataBound="rptHead_ItemDataBound">
                    <ItemTemplate>
                        <div class="mainArea" id="main" runat="server">
                            <p class="Heading">
                                <%# Eval("MainHeading")%></p>
                        </div>
                    </ItemTemplate>
                </asp:Repeater>

C# Code

ItemDataBound method to check the current item index and identify if it is the 5th item then apply CSS class.

protected void rptHead_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                System.Web.UI.HtmlControls.HtmlGenericControl main = (System.Web.UI.HtmlControls.HtmlGenericControl)e.Item.FindControl("mainArea");

                if ((e.Item.ItemIndex + 1) % 5 == 0 && e.Item.ItemIndex != 0)
                {
                    main.Attributes.Add("class", "newcssclass");
                    //Do what ever you want to do
                }
            }
        }

        catch (Exception ex)
        {
        }
    }



Similarly, you can get the nth item in Repeater Control and perform your action on it.

Comments

Popular

What's new in C# 6.0 language - All new features of C# 6.0 for developers

SharePoint Interview Questions and Answers