Search code examples
c#asp.netif-statementasprepeater

how to count value of last column in repeater control in asp.net


Look at the below picture I want to count value of last column (cnt) I am using repeater control.

example:

if (last column (cnt) is greater than 5> )
{
    response.write ("6");
}

sql query

enter image description here

 SELECT id, category, ( SELECT COUNT(id) FROM entry_table WHERE category.id = entry_table.Cat_id) as cnt FROM category

Repeater code

<asp:Repeater ID="CloudTags" runat="server"  OnItemDataBound="CloudTags_ItemDataBound">
    <ItemTemplate>
        <asp:HyperLink ID="HyperLink9" runat="server">
             <%#DataBinder.Eval(Container,"DataItem.Category")%>
            (<%#DataBinder.Eval(Container,"DataItem.cnt")%>)
        </asp:HyperLink>
    </ItemTemplate>
</asp:Repeater>

Code behind:

protected void CloudTags_ItemDataBound(object sender, RepeaterItemEventArgs e)
{

}

Solution

  • You could do something like:

    protected void CloudTags_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        var repeaterItem = e.Item;
        // TODO you still have to check the type of the repeaterItem
        var dataItem = (dynamic) repeaterItem.DataItem;
        var cnt = dataItem.cnt;
        if (cnt > 5)
        {
            var hyperLink = (HyperLink) repeaterItem.FindControl("HyperLink9");
            hyperLink.CssClass = "TagSize2";
        }
    }
    

    or

    protected void CloudTags_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        var repeaterItem = e.Item;
        // TODO you still have to check the type of the repeaterItem
        var dataItem = repeaterItem.DataItem;
        var objCnt = DataBinder.Eval(dataItem, "cnt");
        // TODO check the whole parsing/converting stuff ...
        var stringCnt = objCnt.toString();
        var cnt = int.Parse(stringCnt);
        if (cnt > 5)
        {
            var hyperLink = (HyperLink) repeaterItem.FindControl("HyperLink9");
            hyperLink.CssClass = "TagSize2";
        }
    }
    

    Anyway, I strongly suggest you to not use dynamic or DataBinder.Eval and rather cast the .Data-property to a strong type! Otherwise, this will cause some fancy runtime reflection and will have an impact on the performance!