字符串列表得到一个不同的项目

List of strings get one item distinct

我已经将列表绑定到中继器 (asp.net)

显示是这样的

我想这样绑定

我的代码

<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();

数据源

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

如何操作?

您必须先将 ItemDataBound 事件添加到 Repeater。然后添加一个三元运算符,它将计算全局字符串 previousValue,其先前值为 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>

然后在后面的代码中添加OntItemDataBound方法和全局变量。

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();
}

或者如果你绑定一个List<class>,你需要这样做:

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;
}