Search code examples
c#asp.netlistrepeater

List of strings get one item distinct


i have bind list to repeater (asp.net)

it shows like this

enter image description here

i want to bind like this

enter image description here

My Code

<asp:Repeater ID="RptID" runat="server">
    <ItemTemplate>
        <tr>
            <td><%# Eval("T") %> :</td>
            <td><%# Eval("D") %> :</td>
        </tr>
    </ItemTemplate>
</asp:Repeater>

C#

List<Options> pList = List Type of options;
RptID.DataSource = pList;
RptID.DataBind();

Data Source

public class Options
{
    public string T { get; set; }
    public string D { get; set; }
}

How to do this?


Solution

  • You have to add the ItemDataBound event to the Repeater first. Then add a ternary operator that will evaluate the global string previousValue, that has the previous value of T.

    <asp:Repeater ID="RptID" runat="server" OnItemDataBound="RptID_ItemDataBound">
        <ItemTemplate>
            <tr>
                <td><%# previousValue != Eval("T").ToString() ? Eval("T") + ":" : "" %></td>
                <td><%# Eval("D") %></td>
            </tr>
        </ItemTemplate>
    </asp:Repeater>
    

    Then in code behind add the OntItemDataBound method and the global variable.

    public string previousValue = "";
    
    protected void RptID_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        //cast the item back to a datarowview
        DataRowView item = e.Item.DataItem as DataRowView;
    
        //assign the new value to the global string
        previousValue = item["T"].ToString();
    }
    

    Or if you bind a List<class>, you need to do this:

    protected void RptID_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        //cast the item back to its class
        Options item = e.Item.DataItem as Options;
    
        //assign the new value to the global string
        previousValue = item.T;
    }